2015-03-31 82 views
0

我正在使用sferik的Twitter Gem和plataformatec的Devise GemRails Twitter config global

如果我沒有理解好這個過程中,這裏是我如何做到這一點:當用戶用他的Twitter帳戶登錄,我保存他的令牌,並在數據庫token_secret所以我可以做:

@client = Twitter::REST::Client.new do |config| 
    config.consumer_key = "MY_KEY" 
    config.consumer_secret = "MY_SECRET" 
    config.access_token  = current_user.token 
    config.access_token_secret = current_user.token_secret 
end 

所以每用戶對於@client有不同的config.access_token(_secret)

我的問題是什麼是使每個控制器全球範圍內可用的Twitter客戶端的最佳方式,但只有當用戶登錄

我不能把它放在config/initializers因爲config.access_token(_secret)尚未設置...

感謝您的澄清。

回答

0

解決辦法其實很簡單......

只是在我的ApplicationController中添加一個before_action和檢查,如果用戶登錄或沒有。

class ApplicationController < ActionController::Base 
    before_action :set_twitter_client 

    private 

    def set_twitter_client 
    if user_signed_in? 
     @client = Twitter::REST::Client.new do |config| 
     config.consumer_key = "MY_KEY" 
     config.consumer_secret = "MY_SECRET" 
     config.access_token  = current_user.token 
     config.access_token_secret = current_user.token_secret 
     end 
    end 
    end 

end 
相關問題