trivektor
trivektor

Reputation: 5638

Rails 3.2: requiring different js file in application.js.erb

How do I require different file in application.js.erb in Rails 3.2? I tried the following but it didn't work

<% if Rails.env == production %>
  //= require production_config.js
<% else %>
  //= require other_config.js
<% end %>
//= require jquery
//= require jquery_ujs

Upvotes: 4

Views: 3413

Answers (3)

faron
faron

Reputation: 1059

Sprockets require to set //= require statements from the file beginning, so they aren't working.

You can use ruby methods in such cases: sprokets github

Also it would be better to do it in separate file. Something like this:

application.js

//= require 'config'
//= require 'jquery'

config.js.erb

<% require_asset(Rails.env.production? ? 'production_config' : 'other_config') %>

PS another useful method is depend_on, it helps when your assets need to be recompiled after some other file changes

Ex. if you need some values from rails_config gem

<%
  paths = %w(config/settings.yml config/settings.local.yml config/settings)
  paths.map(&Rails.root.method(:join)).each { |full_path| depend_on(full_path) if File.exist?(full_path) }
%>

Upvotes: 0

Roger
Roger

Reputation: 7612

You can do that, but you need to include the code in your application.html.erb (inside the head action i suggest).

If you add a production_config.js file to your 'asset/javascript' folder, then you can add it using:

<% if Rails.env == production %>
   <%= javascript_include_tag "production_config" %>
<% else %>
  <%= javascript_include_tag "other_config" %>
<% end %>

make sure you don't call it production_config.js.coffee (these get automatically bundled) and don't add it to you application.js either.

Upvotes: 2

kasper375
kasper375

Reputation: 171

Your sample will not work because assets:precompile is before erb translates to clean js. And you have wrong assets syntax. What is //= require 'production_config.rb'? May be it's 'production_config.js'. But you shouldn't write quotes and file extenshions in assets comments.

You can write file config.js.erb and write in it something like this:

<% if Rails.env == production %>
  productionConfig();
<% else %>
  otherConfig();
<% end %>

In your application.js file write simply

//= require config
//= require jquery
//= require jquery_ujs

Upvotes: 4

Related Questions