如何将 Twitter 配置移出控制器?(导轨) [英] How do I move twitter configuration out of the controller? (Rails)

查看:29
本文介绍了如何将 Twitter 配置移出控制器?(导轨)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sferik 的 Twitter Gem.

I am using the Twitter Gem by sferik.

我认为将我的 twitter 应用程序的配置存储在控制器中非常混乱:

I think it's very messy to store the configuration for my twitter app in the controller:

class HomeController < ApplicationController


  def index
    require "twitter"
    client = Twitter::REST::Client.new do |config|
      config.consumer_key        = "###"
      config.consumer_secret     = "###"
      config.access_token        = "###"
      config.access_token_secret = "###"
    end
    @tweets = client.user_timeline( count: 2)
  end

  def show
  end

end

我正在尝试将其存储在/config/initializers/twitter_creds.rb 中:

I'm attempting to store this in /config/initializers/twitter_creds.rb:

require "twitter"
    client = Twitter::REST::Client.new do |config|
      config.consumer_key        = "###"
      config.consumer_secret     = "###"
      config.access_token        = "###"
      config.access_token_secret = "###"
    end

但我不确定这是否正确或我将如何访问控制器中的 twitter 客户端.我注意到一些开发人员使用 .yml 文件来存储配置文件.我正在寻找指导;什么是最佳实践以及如何从我的控制器访问 Twitter 客户端?

But I'm not sure if this is right or how I would access the twitter client within my controller. I've noticed that some developers use .yml files to store configuration files. I'm looking for guidance; what's best practice and how do I access the Twitter client from my controller?

推荐答案

关于你的班级:

最好使用模块来封装推特逻辑.我会像这样更改课程:

Is better you use a module to encapsulate the twitter logic. I would change the class like this:

class HomeController < ApplicationController
  include MyTwitterModule

  def index
    @tweets = user_timeline(2)
  end

  def show
  end

end

模块应该是这样的:

require "twitter"
module MyTwitterModule
  @@client = Twitter::REST::Client.new do |config|
    config.consumer_key        = "###"
    config.consumer_secret     = "###"
    config.access_token        = "###"
    config.access_token_secret = "###"
  end

  def user_timeline(qt)
    @@client.user_timeline(count: qt)
  end
end

这只是一个建议;)

关于存储密钥和令牌:

存储此类信息的更好方法是使用 Rails.env,这样您就可以使用不同的密钥或令牌进行开发和生产,而不是存储在文件中.

The better way to store this kind of information is using Rails.env, with this you can use different keys or tokens for development and production and its not storaged in file.

看看这个 gem,它可以帮助你.

Take a look at this gem, its can help you.

我希望这会有所帮助.

这篇关于如何将 Twitter 配置移出控制器?(导轨)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆