This post describes a quick and dirty approach to better package management for assets. For more rationale behind this, why not look at my post called Better Component Packaging for Rails’ Asset Pipeline.

If you order omakase, the chef’s suggestion is dropping everything in vendor/assets. But manually snatching up several repos is a tedious and unsustainable approach, and Asset Gems (like jquery-rails) who do that for you aren’t available for the vast amount of front-end frameworks.

Twitter Bower is perfectly suited for this use case. Think RubyGems for the front-end. It let’s you resolve packages from a various places like its central registry, github, or just a URL. See the Bower Readme for more.

Be sure you have node.js installed and check out the ruby-bower for more information.

First, download the files from this gist:

$ wget
$ wget -P config/initializers
$ wget -P lib/

In your Gemfile, add

gem 'ruby-bower', group: :assets

Then, run

$ bundle install

Be sure your application’s lib/ directory gets loaded

# In config/application.rb
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Now choose where you want to include your Bower dependencies:

// e.g. in app/assets/javascripts/application.js

//= require_bower_dependencies

Finally, you’re able to use Bower to manage dependencies. They will be included in your scripts.

$ bower install --save angular

Notice that some components don’t declare they dependencies or main files correctly. For these exeptions, you need to require the according file manually. Why not submit a pull request to the library while at it?

// e.g. in app/assets/javascripts/application.js

//= require_bower_dependencies
//= require underscore/underscore

This is basically the approach that spagalloco’s bower gem uses. Check out its sources, they’re really insightful.

blog comments powered by Disqus