Configurable ActiveResource Site Variable

September 16, 2009

flickr

Documentation on ActiveResource is fairly thin on the ground.

If you are using ActiveResource in the real world it is likely that you will want to use different webservices depending on what environment you are in. (Staging, Development, CI, Production etc.)

Heres how to do it. This assumes the REST api has been put under the api namespace and has been setup with HTTP Authentication.

config/initializers/config.rb

raw_config = File.read(RAILS_ROOT + "/config/config.yml")
  GLOBAL = YAML.load(raw_config)
  APP_CONFIG = GLOBAL[Rails.env]

config/config.yml

development:
      webservice: http://username:password@localhost:3001/api/
  test:
      webservice: http://username:password@localhost:3001/api/
  staging:
      webservice: https://username:password@staging.com/api/
  production:
      webservice: https://username:password@production.com/api/

app/models/income_type.rb

class IncomeType < ActiveResource::Base
    self.site = APP_CONFIG['webservice']
  end

Here is a great railscast on the subject.