Default Values for Boolean Options in Ruby

Let’s say you read settings from a YAML file and have some sort of settings object. Then you check if certain options are set with custom values or you have to set default/fall-back values on them. If you are dealing with Boolean options you have to be careful … as I had to find out myself.

Initially you would probably do something like the following to set a default value on a Boolean option:

settings[:some_option] ||= true # set default value if nothing set

Do you see the problem? What happens if the option was deliberately set to

false

? You would overwrite it because both cases

nil

(i.e. nothing set) and

false

would evaluate to

false

in the context of the

||=

operator and you would in both cases assign the right hand value (and overriding an explicit user choice in one case) … *ouch*.

So the correct solution is something like the following:

settings[:some_option] = true if settings[:some_option].nil?

Just be careful … 😀

Render Rails assets to string

If you ever needed a way to render a Rails assets to a string, Hongli Lai from Phusion describes how. 🙂

I prepared a Gist wrapping it into a nice helper. 😀

module ApplicationHelper
  # thanks to http://blog.phusion.nl/2011/08/14/rendering-rails-3-1-assets-to-string/
  # you may need to change the owner of the tmp/cache/* directories to the web servers user
  # e.g. for Debian systems: `chown -R www-data:www-data tmp/cache/*`
  def render_asset(asset)
    Conferator::Application.assets.find_asset(asset).body.html_safe
  end
end