如何在 rails 中输出整个资产管道?

How do I output the entire asset pipeline in rails?

对于这个特定的 rails 项目,我想保存一个 http 请求,所以我想将所有 javascript 输出到 [=16= 中的正文中] 资产管道。

rails有没有办法做到这一点?

不幸的是,由于文件由 Sprocket's server 实时提供,因此您无法在开发中轻松实现此功能,但在生产中实现此功能非常简单:您只需要遍历编译脚本并将它们呈现在 blob 中。

这是一个您可以用来代替 javascript_include_tag 的助手:

module ApplicationHelper
  if Rails.env.production?
    def embedded_javascript_include_tag(*sources)
      options = sources.extract_options!.stringify_keys
      scripts = sources.uniq.map { |source|
        File.read("#{Rails.root}/public/#{javascript_path(source)}")
      }.join("\n").html_safe
      content_tag(:script, scripts, options)
    end
  else
    def embedded_javascript_include_tag(*sources)
      javascript_include_tag(sources)
    end
  end
end

请注意,您仍然需要 运行 rake assets:precompile 才能正常工作。不要忘记设置环境以启用任何 uglifiers 和 minifers! (RAILS_ENV=production rake assets:precompile)