简体   繁体   中英

Loading different Javascript files in Rails based on environment

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

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
...

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM