我有几个与我集成的api,需要在我的应用程序的各个部分调用.
存储密钥,用户/密码或令牌信息(例如配置文件)的方法是什么,然后如何调用它们以便在应用程序的其他部分中使用?
谢谢.
您可以在rails已经使用的机制中存储用户名/密码和类似的配置信息; 您可以东东配置数据直接进入您的环境配置文件(其中production,testing和development配置),或者你可以使用自己的机制:
require "yaml"
config_hash = YAML::load_file("/path/to/your/config.yaml")
Run Code Online (Sandbox Code Playgroud)
最简单的方法是将信息作为常量存储在各种环境文件中。这样您就可以使用不同的帐户进行开发、生产等。
# Eg
# development/environment.rb
....
API_1_USER = "user101"
API_1_PW = "secret!"
Run Code Online (Sandbox Code Playgroud)
另一种方法是创建一个 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!"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10004 次 |
| 最近记录: |