These days almost all web applications uses loads of JavaScripts (like jQuery, AngularJS and so on) and its becoming challenging to maintain the its versions and dependencies. Lets see how we can manage such external JavaScripts assets within a Rails application. I am going to illustrate 3 ways to manage such assets.
They are:
- Bower using bower-rails gem
- Rails assets gem
- Torba
1. Bower with Rails
(Image courtesy: http://www.slideshare.net/ivanoats/bower-and-rails)
What is Bower ?
Bower is package manager, it do find libraries, downloads and save stuffs you are looking for that is configured in a file called bower.json.
Integrating Bower with Rails
I am not going to explain much on how to use bower, assuming you have installed bower using npm.
Integrating bower with rails application is pretty simple, you can use bower-rails gem, by default all the assets that are installed via bower will stay inside vendor/assets/bower_components whether you can go with bower.json or via DSL that allows you to manage Bower components via a Bowerfile.
bower.json
Bowerfile
After you are done with bower.json or Bowerfile run rake bower:install, include the js file names in application.js of your rails app.
application.js
Thats it, now all your assets dependency and versioning information are at the same place and easily maintainable.
2. Using Rails Assets
Rails Assets is a pretty simple and straight forward way of managing your assets and it is quiet new as well. You can have all your assets in your Gemfile itself instead of having it in a separate place, but at the end, it will use bower package to download the library.
It will automatically convert the packaged components into gems that are easily droppable into your asset pipeline and stay up to date.
1) Add the source in your Gemfile
source ‘https://rails-assets.org’
2) Add the bower package name at the end of rails-assets-BOWER_PACKAGE_NAME
gem ‘rails-assets-angular’
3) Run bundle install
This way, you don’t need to run a separate command to install your assets, bundler will take care of that. Pretty simple right?
3. Torba
Torba is another option to manage our assets in Rails. It is a Bower-less asset manager for Sprockets. It makes a local copy of a JS/CSS library and puts it under ‘Sprockets’ load path. Please check https://github.com/torba-rb/torba for more information.
Conclusion
In my opinion, Rails assets is easier and getting quite popular, since we can manage assets in Gemfile, but still Bower also has bower.json very similar to the Gemfile.