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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With