YAML file configuration in ruby & rails

While coding in ruby and rails, we often requires variables to be initialized that can be usedacross 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"
Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby on Rails and tagged , . Bookmark the permalink.

One Response to YAML file configuration in ruby & rails

  1. Dora says:

    I feel so much happier now I undestrnad all this. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s