Rails / Assets pipeline: Dynamically list assets included in a manifest
-
15-06-2021 - |
Question
I'm successfully using assets pipeline for months.
Now I would like to load some of my JS files asynchronously (using yepnope library). It works well when config.assets.debug
is false
.
But in development mode (where config.assets.debug
is usually true
), the best option for me would be to dynamically get a list of all js files included in my manifests (I got 2 manifests: application.js and externals.js) to give them to yepnope for async loading.
Any idea to do so?
Solution
Finally found the answer, I created this helper (read this to see how to declare helper methods visible during asset compilation)
# given a list of Sprockets manifests, returns a flattened array of dependency paths
def paths_for_manifests(manifests = [])
manifests.map do |manifest|
Rails.application.assets[manifest].dependencies.map{|d| "/assets/#{d.logical_path}"}
end.flatten
end
and I use it like this (from a JS / CoffeeScript file):
paths = <%= paths_for_manifests(%w(externals.js application.js)) %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow