views:

47

answers:

2

I have several api's that I am integrating with and need to call in various parts of my application.

What is the way to store the keys, the user/password, or token information, say, a configuration file and then how do I call them for use in other parts of the application?

Thanks.

A: 

Easiest is to store the info as constants in your various environment files. That way you can use different accounts for development, production, etc.

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

Alternative is to create a yaml file, then read it when your app signs in to an api. This is the style used by rails itself with the config/databse.yml file

ADDED

You can also store as a constant using a hash or nested hash.

# 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!"}
Larry K
If taking this approach, I vote for nested hashes, rather than underscored constants.
Matchu
What is an example of a nested hash? And then how would I invoke it in the controller that needs the API access, just as an ALL CAP variable?
Angela
I added an example of using hashes as constants
Larry K
okay, I see now, so when I use in another file, I just put them as described above...cool
Angela
+3  A: 

You can store usernames/passwords and similar configuration information in mechanisms that rails already uses; you can either stuff the configuration data right into your environment configuration files (where production, testing, and development are configured), or you could use your own mechanism and:

require "yaml"
config_hash = YAML::load_file("/path/to/your/config.yaml")
sarnold
Hi, I guess I don't follow what the config.yaml looks like, don't I already have one as the environment configuration file?
Angela
The suggestion is to maintain your own configuration file in YAML. Doing so allows you to separate your app-specific configs from Rails configs.
Chris
okay, I see....so I create my own yaml and put the code in config file?
Angela