The option to share events on Google Calendar is an important feature introduced by Google to as an answer to the changing needs of users as they spend more time and socialize online. This tip demonstrates how to add an event to Google Calendar using Ruby on Rails.
Before starting the application we need to have a Google account. We can create an account at https://www.google.com/accounts/NewAccount . After creating google account we have to register our project at https://code.google.com/apis/console .
Visit the above link and create a new project. The screenshot provided below image should further help you.
Then activate the google calendar api . The below image will describe better. Then create the oauth client id for the application. The below image will demonstrate better. Then change the client id settings. You need to provide the hostname(localhost with port number) or site URL. Refer to the image below. At last change the callback route(url) for the application. Now get the client id and client secret. We are using two gems 'omniauth-google-oauth2' and 'google-api-client'. First gem is used only for authenticating the user and getting the auth token of user's account. Second gem is used for creating the events or getting the user's calendar data. The code snippet below demonstrates how to create event on Google calendar using user auth token.
# POST /events # POST /events.json def create @event = Event.new(params[:event]) respond_to do |format| if @event.save email = @event.attendees.split(",") new_array = [] email.each do |mail| new_array mail } end user = current_user event = { 'summary' => @event.summary, 'location' => @event.location, 'start' => { 'dateTime' => @event.start_date_time.to_datetime.rfc3339}, 'end' => { 'dateTime' => @event.end_date_time.to_datetime.rfc3339}, 'attendees' => new_array } #Use the token from the data to request a list of calendars token = user["token"] client = Google::APIClient.new client.authorization.access_token = token service = client.discovered_api('calendar', 'v3') result = client.execute(:api_method => service.events.insert, :parameters => {'calendarId' => 'primary'}, :body => JSON.dump(event), :headers => {'Content-Type' => 'application/json'}) format.html { redirect_to @event, notice: 'Event was successfully created.' } format.json { render json: @event, status: :created, location: @event } else format.html { render action: "new" } format.json { render json: @event.errors, status: :unprocessable_entity } end end end