问题
I've been struggling a bit with adding Google Analytics to my Rails 4 app (see this post).
I've got it working by adding the JavaScript code, that Google supplies, in a new file in /public/assets/google-analytics.js
. In application.html.erb
I have included:
<%= javascript_include_tag 'google-analytics' if Rails.env.production? %>
This works but I thus haven't included the JavaScript file in app/assets/javascripts/
and placed it in the public folder instead. The JavaScript file thus isn't compiled.
Would you say that this is good practice / the Rails way?
I choose this solution because otherwise I could only get it to work if I also added Rails.application.config.assets.precompile += ['google-analytics.js']
to config/environments/production.rb (it didn't work if I added this to the initializer assets.rb). An I find this a bit more cluttering than the above solution.
回答1:
In your case it might be best to just add the analytics script to the head section of views/layouts/application.html.erb
Another option would be to create a view/shared directory with a file called _analytics.hml.erb and paste the analytics tag in there and do this in your views where you need it:
<%= render 'shared/analytics' %>
No need to precompile it at all if you just render it in a partial. What is 'best practice' is subject to opinion, but if you render it in a partial you'll ave yourself some time configuring and troubleshooting the way you're trying to do it.
In my opinion, the partial is the more 'Railsy' way, unless you specifically need someone to be able to access www.your-site.com/analytics.js
来源:https://stackoverflow.com/questions/31456598/rails-asset-pipeline-can-it-be-good-practice-to-include-asset-in-public-folder