Wednesday, October 10, 2012

Rails initialization from yml configurations

Rails' startup initialization may read configurations from yml files.  For example, on development environment, developers may want exception notifications only be send to himself/herself.

So, developer may create a /config/config.yml (if not exists) for local development while commits a /config/config.yml.example for source control.  Then in config.yml, create a section like:

development:
    exception_email_recipient: someone@example.com


Next, in /config/initializers/exception_notification.rb, read the config from yml, like this:

filepath = "#{Rails.root.to_s}/config/config.yml"
local_config = YAML.load_file(filepath)
exception_email_to = local_config[Rails.env]['exception_notification_email_to']

Merlot::Application.config.middleware.use ExceptionNotifier,
    :email_prefix => "[Project_name][#{Socket.gethostname}] ",
    :sender_address => %{"Exception" <exception@example.com>},
    :exception_recipients => [ exception_email_to || 'production_recipient@example.com' ]


In this way, on exception emails goes to 'someone@example.com' on development platform.  While on production, it will goes to 'production_recipient@example.com'.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.