I have a fragment of JavaScript that I want to add to a page, but only in the production environment. Does rails have a way to insert or conditionally include on deployment. I know I could do "if Rails.env.production?" But I'd rather not do this condition check every time the page is loaded.
A:
What I do in this situation is create a constant in each environment's config file:
#config/environments/development.rb
SNIPPET = ""
#config/environments/production.rb
SNIPPET = "<script src='whatever.js'></script>"
#app/views/file.html.erb
<%= SNIPPET %>
Ben
2009-12-30 23:41:23
I don't like the idea of putting view code in the config files. This is what view helpers are FOR.
Sarah Mei
2010-01-18 04:56:14
Sure, that's fair. Really what I'm trying to impart is: don't do conditional logic based on RAILS_ENV in views. That's what the environment config files are FOR :-)
Ben
2010-01-18 22:07:24
+4
A:
I wouldn't be worried about the overhead of one if
statement.
Why not use a custom helper method:
def snippet
if RAILS_ENV == "production"
javascript_tag "whatever"
elsif . . .
end
then you can use the same syntax:
<%= snippet %>
and you get a couple benefits:
- access to other rails helpers
- your config file won't be littered with raw html
klochner
2009-12-31 00:36:55