How can I dynamically require assets in the Rails 3.1 asset pipeline?

你。 提交于 2019-12-03 02:46:00

OK, so here's the solution:

Internally, the asset pipeline (aka Sprockets) require directive calls context.require_asset() to actually require whatever path is specified in the directive. Turns out, that means that the require_asset method is present and available during ERB expansion. So, the correct solution was:

// ... Standard application.js stuff here ...
//= require_tree .
<%
Rails.plugins.each do |plugin|
  require_asset(plugin.to_s)
end
%>

Added that in, and all worked as expected. Whew!

In case you're wondering about that Rails.plugins bit, I added an extension to the Rails module to get the actual list of plugins that are loaded, in load order, based on config.plugins. For completeness, here it is:

module Rails
  def self.plugins
    # Get sorted list of all installed plugins
    all = Dir.glob(Rails.path('vendor/plugins/*/init.rb')).collect {|p| p.extract(/\/([^\/]+)\/init.rb$/) }
    all.sort!
    all.collect! {|p| p.to_sym }

    # Get our load order specification
    load_order = Rails.application.config.plugins

    # Split the load order out, and re-assemble replacing the :all keyword with the
    # set of plugins not in head or tail
    head, tail = load_order.split(:all)
    all -= head
    all -= tail

    # All set!
    head + all + tail
  end
end

And the final detail was creating a <plugin_name>.js manifest file in each plugin's app/assets/javascripts directory.

Hope that helps someone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!