public
Created

Environment-based initializers in Rails - USE THEM!

  • Download Gist
old_school_use.rb
Ruby
1 2 3 4
# what? why does your production code care what environment it is in? SILLY!
unless Rails.development? || Rails.test?
Slottd::CreatesReservationTimer.for(slot.id)
end
the_better_way.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12
# in code, no more environment check
Slottd::CreatesReservationTimer.for(slot.id)
 
# in config/development.rb
module Slottd
CreatesReservationTimer = Timers::Null
end
 
# in config/production.rb
module Slottd
CreatesReservationTimer = Timers::IronWorker
end

I like the way the "production" code ends up, but having the constant defined via initializer would likely surprise me. At least the first time I discovered it. And every time I forgot and re-discovered it. Probably worth it though.

...and the 'old_school_use' has the advantage of having it all together, and making reading easier.

jb

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.