Saturday, October 27, 2007

RailsMode (not ENV['RAILS_ENV'])

I've been spreading things like this all around my code, where I wanted to do something differently in production vs. development mode. Previously, I'd write something like this:

if ENV['RAILS_ENV'] == 'production'
  # perform magic, in production mode ...
end

While this is pretty simple, it just didn't feel very DRY. So, I decided to use this as a reason to learn about modules and mixins.

I have a generic plug-in in vendor/plugins that I put small bits of code like this. You might as well, but if you don't, you can drop this in a file in lib or in a helper.

module RailsMode
  def railsmode(*list)
    list.map! do |item|
      item.to_s
    end

    if block_given?
      if list.include?(ENV['RAILS_ENV'])
        yield
      end
    else
      return list.include?(ENV['RAILS_ENV'])
    end
  end
end

I also put this line in my environment.rb file:

include RailsMode

This mixes the module into the current class. Doing this in environment.rb makes it available everywhere in rails. Putting that line in a specific file would also work, such as a controller, or a helper.

With this, I can now write:

if railsmode(:production)
  # perform magic, in production mode ...
end

I can also check for multiple modes at once:

if railsmode(:production, :development)
  # perform magic, in production or development ...
end

And of course, who needs an if when I can pass in a block:

railsmode(:production) do
  # perform magic, in production mode ...
end

No comments:

Post a Comment