Rails资产管道:将资产包含在公用文件夹中而不是资产文件夹中是一种好习惯吗?

编程入门 行业动态 更新时间:2024-10-28 08:31:10
本文介绍了Rails资产管道:将资产包含在公用文件夹中而不是资产文件夹中是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在努力将Google Analytics(分析)添加到我的Rails 4应用程序中(请参阅这篇文章).

I've been struggling a bit with adding Google Analytics to my Rails 4 app (see this post).

我可以通过在/public/assets/google-analytics.js中的新文件中添加Google提供的JavaScript代码来使其工作.在application.html.erb中,我包括了:

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? %>

这可行,但是我没有将JavaScript文件包含在app/assets/javascripts/中,而是将其放置在公用文件夹中.因此,JavaScript文件未编译.

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.

您会说这是一种很好的做法吗/Rails的方式吗?

Would you say that this is good practice / the Rails way?

之所以选择此解决方案,是因为否则只有在将Rails.application.config.assets.precompile += ['google-analytics.js']添加到config/environments/production.rb中时,它才能正常工作(如果将它添加到初始化程序asset.rb中,则不起作用).我发现这比上面的解决方案更混乱.

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.

推荐答案

在您的情况下,最好将分析脚本添加到views/layouts/application.html.erb的开头部分

In your case it might be best to just add the analytics script to the head section of views/layouts/application.html.erb

另一种选择是使用一个名为_analytics.hml.erb的文件创建一个视图/共享目录,并将analytics标记粘贴到该目录中,然后在您需要的视图中执行此操作:

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' %>

如果仅部分渲染它,则根本不需要对其进行预编译.什么是最佳实践"尚有待商opinion,但如果将其部分渲染,则将花费一些时间来配置和解决尝试执行此操作的方式.

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.

在我看来,部分使用的是"Railsy"方式,除非您特别需要某人才能访问www.your-site/analytics.js

In my opinion, the partial is the more 'Railsy' way, unless you specifically need someone to be able to access www.your-site/analytics.js

更多推荐

Rails资产管道:将资产包含在公用文件夹中而不是资产文件夹中是一种好习惯吗?

本文发布于:2023-07-12 07:23:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1096846.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:资产   文件   是一种   夹中   管道

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!