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"
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.
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.
Sprockets is a Rack-based asset packaging system that concatenates and serves JavaScript, CoffeeScript, CSS, LESS, Sass, and SCSS.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With