Tuesday, November 17, 2009

YAML file configuration in ruby & rails

by Sandip Ransing 0 comments
Tags

While coding in ruby and rails, we often requires variables to be initialized that can be used across application. There are many ways to define configuration variables

1. Initialize variables inside environment file
  # This agencies can be used across application
  AGENCIES = ['TIMES NEWS NETWORK', 'AGENCIES', 'AFP', 'PTI']

  # Configuration for html nodes

  Article_title_tag = "h1.heading"
  Date_auth_agency_tag = "span[@class='byline']"
  Location_content_tag = "div[@class='Normal']"
2. Inside config/initializers/config.rb. Just make config.rb inside initializers and add variables to it.
  #config/initializers/config.rb
  # This agencies can be used across application
  AGENCIES = ['TIMES NEWS NETWORK', 'AGENCIES', 'AFP', 'PTI']

  # Configuration for html nodes
  Article_title_tag = "h1.heading"
  Date_auth_agency_tag = "span[@class='byline']"
  Location_content_tag = "div[@class='Normal']"
3. But most efficient way to organize variables is YML file.
# config/config.yml
the_times_of_india:
  article_title_tag: h1.heading
  date_auth_agency_tag: span[@class='byline']
  loc_content_tag: div[@class='Normal']
Accessing YML files
 # config/initializers/load_config.rb
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")
=> true
>> APP_CONFIG
=> {"the_times_of_india"=>{"article_title_tag"=>"h1.heading", "loc_content_tag"=>"div[@class='Normal']", "date_auth_agency_tag"=>"span[@class='byline']"}}
>> APP_CONFIG[:the_times_of_india]
=> nil
>> APP_CONFIG['the_times_of_india']
=> {"article_title_tag"=>"h1.heading", "loc_content_tag"=>"div[@class='Normal']", "date_auth_agency_tag"=>"span[@class='byline']"}
>> APP_CONFIG['the_times_of_india']['article_title_tag']
=> "h1.heading"

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter