LoginSignup
12
15

More than 5 years have passed since last update.

Rails4 + fullcalendarでカレンダーアプリを作る(1)

Last updated at Posted at 2014-11-04

*追記、更新
  曖昧な部分があったので修正、fullcalnedarの最新版に対応しました。

概要

Rails4.1.0でGoogle Calendar APIとfulcalendarを使ってカレンダーアプリを作成する

環境

Rails v4.1.0
Ruby v2.0.0
fullcalendar v2.3
Calendar aPI v3
Devise
google-oauth

経緯

ネットで探しても日本語の情報がかなり少ないうえに、最初の触りしか情報がないので、普段カレンダーをメインでイジリ倒したりしている僕が書いていこうと思った。

使い方

今回はgoogleのoauth認証と合わせてfullcalendarを利用します。
googleのoauth認証は他に情報が多々あるのでググってください。
Webサービスを作るのでDeviseを使ってユーザーをDBに保存するようにしています。

カレンダーは一言でいうと「複雑」です。
イベントの登録、更新、削除、繰り返しが入ってくるとカオスになってくるので、リファクタリングをしながらやっていきたいと思います。
今回はとりあえずログイン後にAjaxでGoogleカレンダーのイベントを取得し、一覧をfullcalendar上に表示するまでを行いたいと思います。

  
fullcalendarの『event』オプションのurlrailsのアクションを指定

calendar.js
eventSources:
        [
            {
                url: 'gcals/get_google_calendar_event',
                dataType: 'json',
                type: 'get'
            },
        ],

  

ルート

routes.rb
get 'gcals/get_google_calendar_event'  =>  'gcals#get_google_calendar_event'

  

GoogleCalebdarAPIからイベントリストを持ってくる

gcal.rb
require 'rubygems'
require 'google/api_client'
require 'yaml'
require 'date'

class Gcal < ActiveRecord::Base

    belongs_to :user
    has_many :events

    #client初期化
  def initialize(user)
    @user = user
    oauth_yaml  = YAML.load_file('config/secrets.yml')
    @client = Google::APIClient.new(application_name:oauth_yaml[Rails.env]["application_name"],application_version: 1)
    @client.authorization.client_id = oauth_yaml[Rails.env]["google_client_id"]
    @client.authorization.client_secret = oauth_yaml[Rails.env]["google_client_secret"]
    @client.authorization.scope = 'https://www.googleapis.com/auth/calendar'
    @client.authorization.access_token  = user.token
    @client.authorization.refresh_token = user.google_refresh_token
    if @client.authorization.refresh_token && user.google_access_token_expire < Time.zone.now
      @client.authorization.fetch_access_token!
      @update_user = User.where(email: user.email).first
      @update_user.update(token: @client.authorization.access_token)
    end
    @service = @client.discovered_api('calendar', 'v3')
  end

  #イベント一覧をgoogleから取得するメソッドを定義

  def get_event_list_from_api(calendar_id,start_time,end_time)
      page_token = nil
      result = @client.execute( :api_method => @service.events.list,
                                :parameters =>
                                 {
                                  'calendarId' => calendar_id,
                                  'timeMax'    => start_time,
                                  'timeMin'    => end_time
                                 }
                              )
      events = result.data.items
      fullcalendar_events = []
      events.each do |e|
        event = {
                 "id"=> e.id,
                 "title" => e.summary
                }
        if e.start["dateTime"] && e.end["dateTime"] #終日かどうか?
           event.start = e.start["dateTime"]
           event.end = e.end["dateTime"]
        else
           event.start = e.start["date"]
           event.end = e.end["date"]
        end
        fullcalendar_events << event
      end
      fullcalendar_events     
   end

  

最後にcontoller

gcals_contoroller.rb
def get_google_calendar_event
    now = Time.zone.now
    start_time = now - 1.month
    end_time = now + 3.month
   #過去1ヶ月〜先の3ヶ月の合計4ヶ月分のイベントを取ってくる
    google_events  = Gcal.new(current_user).get_event_list_from_api(current_user.email,start_time,end_time)
    render :json => google_events
  end

  
  
GoogleCalendarAPIから飛んでくるパラメーターは

fullcalendarで表示するためにはパラメーターを"title","start","end"などの

EventObjectに変換しないとそのままではfullcalendarに反映されません。

fullcalendarの形式に合わせて文字列を成形すれば大丈夫ですね。

12
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
15