Reputation: 1381
I'm use Rails 3.2 built in sprockets functionality to compile static assets. Is it possible to compile javascript with environment specific variables?
So I would like to do something like this
/assets/javascripts/myfile.js
//lots of code
script.src =
('https:' == document.location.protocol ? 'https://' : 'http://') +
'some.metrics.site/projects/<%=ENV_SPECIFIC_TOKEN%>.js';
//lots of other code
Upvotes: 2
Views: 1211
Reputation: 75
Any update for this issue?
Using the .erb extension solves the problem but not when you precompile assets.
In my case, I need to precompile the assets for my staging environment. When I do rake assets:precompile RAILS_ENV=staging, I can see in the js assets generated that my environment variable is not defined and thus the string interpolation results in an empty string.
The problem is (I think) that the environment variable definition is in config/application.rb, which is not called while generating assets.
I think that the gem Capistrano may help by adding some tasks before generating the assets, but if we can define some environment variables while generating the assets (in the CLI for example), it would be better.
Upvotes: 0
Reputation: 44880
Sprockets lets you append any number of preprocessors to a filename. Add a .erb
to the end, and it will be first interpreted as ERB and then output as a JavaScript file.
mv assets/javascripts/myfile.js assets/javascripts/myfile.js.erb
Check out the Rails Asset Pipeline guide on JavaScript/CoffeeScript and ERB.
Upvotes: 1