如何在Rails中存储API的密钥?

我有几个与我集成的api,需要在我的应用程序的各个部分调用。

存储密钥,用户/密码或令牌信息(例如配置文件)的方法是什么,然后如何调用它们以便在应用程序的其他部分中使用?

谢谢。

最简单的方法是将信息作为常量存储在各种环境文件中。 这样您就可以使用不同的帐户进行开发,生产等。

# Eg # development/environment.rb .... API_1_USER = "user101" API_1_PW = "secret!" 

另一种方法是创建一个yaml文件,然后在你的应用登录到api时读取它。 这是rails本身使用config / databse.yml文件的样式

添加

您还可以使用散列或嵌套散列作为常量存储。

 # Eg # development/environment.rb .... API_1 = {"user" => "user101", "pw" => "secret!"} API_2 = {"user" => "user102", "pw" => "double_secret"} # or nested hashes API_KEYS = { "api_1" => {"user" => "user101", "pw" => "secret!"}, "api_2" => {"user" => "user102", "pw" => "double_secret"}} # using them in another file: foo.signin(API_1['user'], API_1['pw']) # or foo.signin(API_KEYS["api_1"]['user'], API_KEYS["api_1"]['pw']) # note, I use string constants instead of symbols to save vm (since the hash is # not referenced more than once or twice). You could also use # symbols as the keys, especially if the hash will be referenced often: API_1 = {:user => "user101", :pw => "secret!"} 

为了使这个问题保持最新,在Rails 4.1中有一种新的方法:

从Rails指南 :

Rails 4.1在config文件夹中生成一个新的secrets.yml文件。 默认情况下,此文件包含应用程序的secret_key_base,但它也可用于存储其他机密,例如外部API的访问密钥。

您可以在rails已经使用的机制中存储用户名/密码和类似的配置信息; 您可以将配置数据填入您的环境配置文件(配置productiontestingdevelopment ),或者您可以使用自己的机制和:

 require "yaml" config_hash = YAML::load_file("/path/to/your/config.yaml") 

查看Configatron ,它非常棒,可以完全用于此目的。