Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 954
Ingo Avatar asked Feb 10 '23 14:02

Ingo


2 Answers

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
...
like image 114
Sharvy Ahmed Avatar answered Feb 13 '23 05:02

Sharvy Ahmed


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 
like image 23
DickieBoy Avatar answered Feb 13 '23 04:02

DickieBoy