philnash / bitly

🗜 A Ruby wrapper for the bit.ly API
https://rubygems.org/gems/bitly
MIT License
451 stars 139 forks source link

Configuring through initializer isn't working #41

Closed mehulkar closed 11 years ago

mehulkar commented 11 years ago

Hey, I might be doing something wrong, but I'm not able to configure a Bitly.client through an initializer.

I have config/initializers/secrets.rb with the following:

if Rails.env == "development"
  ENV['BITLY_USERNAME'] = user_name
  ENV['BITLY_API_KEY']  = api_key
end

I'm getting both from https://bitly.com/a/your_api_key.

And I have config/initializers/bitly.rb with this:

Bitly.configure do |config|
  config.api_version = 3
  config.login = ENV['BITLY_USERNAME']
  config.api_key = ENV['BITLY_API_KEY']
end

When I launch a Rails console, the env variables are correctly set, but initializing a new client with Bitly.client doesn't seem to be using the login credentials. It returns:

<Bitly::V3::Client:0x007ff960af3230 @default_query_opts={:login=>nil, :apiKey=>nil}>
philnash commented 11 years ago

Are you sure that config/initializers/secrets.rb is being run before config/initializers/bitly.rb? If secrets.rb is run second you will see the ENV variables present in the console but the Bitly configure block would have just seen them as nil.

Can you try commenting out the configure block from your initializer, starting a console and running the configure block in there, then try to make a client with Bitly.client.

mehulkar commented 11 years ago

@philnash I didn't know how Rails what order Rails was loading initializers in. I changed secrets.rb to 00_secrets.rb and now it works!

Thank you!

I'll open another issue, but jmp_url doesn't work with api version 3.

philnash commented 11 years ago

I wouldn't trust the load order of those initializers regardless. Would it not be better to combine your secrets.rb file with bitly.rb and initialize your environment variables directly before you try to use them so that you can guarantee they exist?

Thanks for raising the other issue, I'll take a look at that now.

mehulkar commented 11 years ago

The reason I have them separate is so I can keep secrets.rb out of source control. I have a bunch of 3rd party API keys and it's nice to keep them organized like that. The other option would be to make duplicates of each file. One that used the ENV vars and the other with the actual keys and wrap them in a if Rails.env == "production" or something like that. I'm not yet sure how to handle it properly.

philnash commented 11 years ago

You could look into using something like figaro to look after ENV variables for your development environment. It handles that sort of thing for you quite nicely. I haven't used it myself, but it's very similar to something we wrote at work that works well for us.

mehulkar commented 11 years ago

Ahh, very nice. Thanks for that link @philnash!