1

我有一個導軌應用程序。我試圖調整不同的模型和控制器。我可以讓事情發揮作用,但我不確定我是否採用了首選方式。所以我有一個event.rb用於我自己的應用程序fullcalendar,在那裏我可以刪除新事件,併爲omniauth授權(本例中爲谷歌日曆)提供social.rb。我試圖在我的fullcalendar中顯示gcal事件,所以根據social.rb數據(標記,鍵),我調用一個API調用google來獲取gcal事件時間,然後在events/index頁面中顯示數據(fullcalendar )。導軌調用方法控制器vs模型

下面是我的兩個方法,我不知道如何放置在我的應用程序中。我的問題(我有3個,因爲它們緊密相連):

  • 方法類型。正如我看到init_google_api_calendar_client應該是一個類方法,如果我把它放到social.rb(我甚至不知道是否應該把它放在那裏)。對於get_busy_events,我根本無法確定要使用的類型。
  • 我想我應該把這些方法放在模型/模塊中,但哪一個(社會/事件/別的東西)?
  • 我應該如何調用這些方法?
events_controller

def index 
    @user = current_user 
    @google = @user.socials.where(provider: "google_oauth2").first 
    @client = Social.init_google_api_calendar_client(@google) ### Is this the proper way to call this method? 
    @get_busy_times = #####how to call the get_buys_events method? 
    @event = Event.new 
    @events = Event.allevents(current_user) 
    respond_to do |format| 
     format.html 
     format.json { render json: @events } 
     format.js 
    end 
    end 

social.rb

def self.init_google_api_calendar_client(google_account) 
    #method only called if google_oauth2 social exists 
    client = Google::APIClient.new 
    client.authorization.access_token = google_account.token 
    client.authorization.client_id = ENV['GOOGLE_API_KEY'] 
    client.authorization.client_secret = ENV['GOOGLE_API_SECRET'] 
    client.authorization.refresh_token = google_account.refresh_token 
    return client 
    end 

如果把這種方法嗎?應該是類/實例嗎?應該如何調用?

def get_busy_events(client) 
    service = client.discovered_api('calendar', 'v3') 
    result = client.execute(
     api_method: service.freebusy.query, 
     body_object: { timeMin: start_at, 
        timeMax: end_at, 
        items: items}, 
     headers: {'Content-Type' => 'application/json'}) 
    end 

回答

2

你問一個很好的問題,在我的經驗,是不是在Rails社區對在何處放置代碼,使服務器端API調用第三方服務普遍採用的慣例。

當您的應用程序以可以異步的方式使用外部API時,可以直接使用ActiveJob或像sidekiq這樣的寶石調用這些調用。這裏有一個體面的寫法(請參閱標題爲「與外部API交談」部分):https://blog.codeship.com/how-to-use-rails-active-job/

但是,如果您正在構建真正依賴於第三方API的應用程序,並且異步調用不會爲您提供太多好處,那麼我建議定義一個不是模型,視圖或控制器的不同類型的類。在沒有寶石滿足您的需求時遵循的常見做法是爲保存在lib文件夾下的API編寫一個ruby包裝類。保持模型方法的範圍爲需要數據庫交互性的邏輯。從控制器調用模型方法以及在包裝類中定義的webservice方法。

祝你好運!

+0

肖恩,thx!你能給我發一篇好文章給第二個版本嗎?對於這個功能,我需要這種方法(儘管我將使用sidekiq進行電子郵件通知)。 –

+0

當然。這個是約會幾年,但遵循約定做得很好,而且很具描述性:http://code.tutsplus.com/articles/writing-an-api-wrapper-in-ruby-with-tdd--net- 23875 –