views:

65

answers:

2

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
I don't like the idea of putting view code in the config files. This is what view helpers are FOR.
Sarah Mei
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
+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
Actually, that's similar to what I have, but I was trying to avoid the "if" check.
rornoob
If you're really concerned, try timing it with and without the "if", and I'm guessing you won't get a noticable difference.
klochner