Thursday, August 8, 2013

List All Files in Gems Loaded in Ruby

We were just saying that we needed to find the paths of all assets loaded in gems in Rails. Easy!

You don't even need Rails to get a list of files included in each gem; that's in the gemspecs: {|name,gspec| gspec.files.collect{|p| File.join(gspec.full_gem_path, p)}}

To output one on each line: {|name,gspec| gspec.files.collect{|p| File.join(gspec.full_gem_path, p)}}.each {|fqpname|puts fqpname}

As a JSON string of relative pathname to f.q. pathname:

gem_map = {}
Gem.loaded_specs.each {|name,gspec| gspec.files.each{|p| gem_map[p] = File.join(gspec.full_gem_path, p)}}
puts gem_map.to_json.to_s

Try it out in rails console.

And as Tommy noted to me, Rails.application.assets can be used also in Rails to get at similar info:

2.0.0p247 :001 > Rails.application.assets['application.js'].dependencies[0].pathname
=> #<Pathname:/(path to gems)/(gem name and version)/vendor/assets/javascripts/some_file.js>

and it can provide the digest for each asset. Rails.application.assets is Sprockets::Environment and Rails.application.config.assets is Sprockets::Railtie::OrderedOptionst which both are interesting to check into if you want more access to assets that Rails manages (note: linked to the latest version which might not be appropriate for your version of Rails- look at your Gemspec.lock). Don't forget to re-read the asset pipeline docs which had awesome tips.

No comments: