Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprockets/Rails: Find all files Sprockets knows how to compile

For Konacha, a Rails engine for testing Rails apps, we need a way to find all files that Sprockets can compile to JavaScript.

Right now we use something like

Dir['spec/javascripts/**/*_spec.*']

but this picks up .bak, .orig, and other backup files.

Can Sprockets tell us somehow whether it knows how to compile a file, so that backup files would be automatically excluded?

content_type_of doesn't help:

Rails.application.assets.content_type_of('test/javascripts/foo.js.bak')
=> "application/javascript"
like image 921
Jo Liss Avatar asked Jun 12 '12 10:06

Jo Liss


People also ask

What are rails Sprockets?

Sprockets is a Ruby library for compiling and serving web assets. It features declarative dependency management for JavaScript and CSS assets, as well as a powerful preprocessor pipeline that allows you to write assets in languages like CoffeeScript, Sass and SCSS.

What does rake assets Precompile do?

By default, Rails uses CoffeeScript for JavaScript and SCSS for CSS. DHH has a great introduction during his keynote for RailsConf. The Rails asset pipeline provides an assets:precompile rake task to allow assets to be compiled and cached up front rather than compiled every time the app boots.

What is sprockets gem?

Sprockets is a Rack-based asset packaging system that concatenates and serves JavaScript, CoffeeScript, CSS, LESS, Sass, and SCSS.


1 Answers

You can iterate through all the files in a Sprockets::Environment's load path using the each_file method:

Rails.application.assets.each_file { |pathname| ... }

The block will be invoked with a Pathname instance for the fully expanded path of each file in the load path.

each_file returns an Enumerator, so you can skip the block and get an array with to_a, or call include? on it. For example, to check whether a file is in the load path:

assets = Rails.application.assets
pathname1 = Pathname.new("test/javascripts/foo.js").expand_path
pathname2 = Pathname.new("test/javascripts/foo.js.bak").expand_path
assets.each_file.include?(pathname1) # => true
assets.each_file.include?(pathname2) # => false
like image 120
Sam Stephenson Avatar answered Sep 23 '22 11:09

Sam Stephenson