Peter Marklund

Peter Marklund's Home


Rails Configuration: Yielding self in initializer

I've come across situations in Rails where you want to repeatedly invoke methods on some class with a long name and it gets ugly and tedious that you have to repeat the class name on every line. I just realized that unlike in the config/environments files the config object is not available in the config/initializer files. I use the AppConfig plugin to parameterize my application and I came up with the yield_self method to make my config/intializers/app_config.rb more readable:

# Method to supplement the app_config plugin. I want to crash early and be alerted if
# I have forgotten to define a parameter in an environment.
def config_param(name)
  AppConfig.param(name) do
    raise("No app_config param '#{name}' defined in environment #{RAILS_ENV}, " +
      "please define it in config/environments/#{RAILS_ENV}.rb and restart the server")

class Object
  def yield_self
    yield self

AppConfig::Base.yield_self do |config|
  config.site_name = "Simple Signup"
  config.admin_email = '"Simple Signup" <>'
  config.exception_emails = %w(
  config.email_prefix = "[#{config.site_name}]"
  config.signup_timeout = 5
  config.send_activate_email = false

  config.transaction_fee = lambda do |price|
    price.blank? ? 0.0 : [10.0, 5.0+0.035*price.to_f].max.round(2)

  config.bank_fee = lambda do |price, card|

ExceptionNotifier.exception_recipients = config_param(:exception_emails)
ExceptionNotifier.sender_address = %{}
ExceptionNotifier.email_prefix = "#{config_param(:email_prefix)} ERROR: "

The method config_param might be more appropriately named app_config. That will be a refactoring for another day though.