f l a m e . o r g

organized flames

RailsMode (not ENV['RAILS_ENV'])

Posted on October 27, 2007

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:

1 if ENV['RAILS_ENV'] == 'production'
2   ... perform magic ...
3 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 helper.

 1 module RailsMode
 2   def railsmode(*list)
 3     list.map! do |item|
 4       item.to_s
 5     end
 6 
 7     if block_given?
 8       if list.include?(ENV['RAILS_ENV'])
 9         yield
10       end
11     else
12       return list.include?(ENV['RAILS_ENV'])
13     end
14   end
15 end

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

1 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:

1 if railsmode(:production)
2   ... perform magic ...
3 end

I can also check for multiple modes at once:

1 if railsmode(:production, :development)
2   ... perform magic ...
3 end

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

1 railsmode(:production) do
2   ... perform magic ...
3 end