Creating list or paths of stylesheets and javascript files in Rails 4

I am writing a Rails4 application that uses a custom cache manifest file that needs to contain links to all the required Javascript and CSS files. Due to the nature of the application, the Rack Offline gem cannot be used.

Calls stylesheet_link_tag

and javascript_include_tag

creates the correct list of files (generated by the asset pipeline), but inserts them into HTML tags.

Is there a way to get the paths to all the compiled javascript and stylesheet files in the controller?

eg.

/assets/custom.css?body=1
/assets/incidents.css?body=1
/assets/users.css?body=1
/assets/application.css?body=
/assets/jquery.js?body=1
/assets/bootstrap/affix.js?body=1
...

      

+3


source to share


2 answers


It was fun! Had to go into the Sprockets source to figure it out.

asset_list = Rails.application.assets.each_logical_path(*Rails.application.config.assets).to_a

      

Then you can grep through the asset list, for example:

asset_list.grep(/\.(js|css)/)

      



EDIT:

If you need hex digests, you can do something like:

environment = Rails.application.assets
asset_list = environment.each_logical_path(*Rails.application.config.assets).to_a
asset_list.map! { |asset| environment.find_asset(asset).digest_path rescue nil }.compact

      

+4


source


Based on research by @kdeisz, this code worked in the controller for the manifest file:

@assets = Rails.application.assets.each_logical_path(*Rails.application.config.assets).to_a
@assets = @assets.map{ |p| view_context.compute_asset_path(p) }
render 'manifest.text', content_type: 'text/cache-manifest'

      



The function is compute_asset_path

needed to get the actual path to resources.

Note. I haven't tested this in production yet. It works in development mode if you installedconfig.assets.debug = false

0


source







All Articles