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.
AppConfig.param(name) do
raise("No app_config param ' ' defined in environment , " +
"please define it in config/environments/ .rb and restart the server")
end
end
yield self
end
end
AppConfig::Base.yield_self do |config|
config.site_name = "Simple Signup"
config.admin_email = '"Simple Signup" <info@simplesignup.se>'
config.exception_emails = %w(info@simplesignup.se)
config.email_prefix = "[ ]"
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)
end
config.bank_fee = lambda do |price, card|
0.0
end
end
ExceptionNotifier.exception_recipients = config_param(:exception_emails)
ExceptionNotifier.sender_address = %{peter_marklund@fastmail.fm}
ExceptionNotifier.email_prefix = " ERROR: "
The method config_param might be more appropriately named app_config. That will be a refactoring for another day though.