4

What is the best way to load a different Javascript file based on your environment (production or development) in Rails 3.2? I'm trying to create a global (yes, global) javascript variable which should vary based on environment. That variable is called by JQuery but is required by some other javascript files I've written.

Is it best to generate an application.js.erb which is dynamic based on the environment we are running or am I missing something?

Thanks

2 Answers 2

5

What is the best way to load a different JavaScript file based on your environment (production or development) in Rails 3.2?

In your application layout, you can add environment specific js file like this:

<% if Rails.env.development? %>
  <%= javascript_include_tag 'development.js' %>
<% end %>

Or more cleaner way:

<% javascript_include_file "#{RAILS_ENV}.js" %>

You can achieve the same result in another way by creating a specific js file and requiring that in application.js.erb:

env_config.js.erb

<%= Rails.env.production? ? 'productionConf();' : 'regularConf();' %>

application.js.erb

//= require env_config
//= require jquery
...
Sign up to request clarification or add additional context in comments.

Comments

3

Instead of loading a different js file, set a variable based on the different environment

I would recommend using gon Its an easy way of getting rails variables into js.

After setting up, do something in your controller like:

before_filter :set_gon_env

def set_gon_env
  gon.rails_env = ENV['RAILS_ENV'] == 'development' ? "dev" : "not dev"
end 

1 Comment

using gon is more idiomatic than other solutions. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.