I'm pretty new to Rails and I'm not sure what is best practice when it comes to adding assets.
Can anybody tell me the advantages and disadvantages of having Javascripts within the assets vs using corresponding gem?
I find gems for pretty much all javascript libraries I want to use. For example, IntroJS. Should I go with the gem or download the javascript and have the library in my assets?
If the gem does not provide any helpers or generators, then it's typically just a convenience that allows you to easily update the version of the assets via the Gemfile. This is nice, as long as the gem itself is relatively close in version to the actual source.
I usually start with the gem, make sure it's being updated regularly, and then move to the source if I really need to.
I've also recently started using bower for some JS sources, and there is a complementary bower-rails gem that provides some bundler like capabilities. Pretty sweet actually!
I have preferred using direct javascript sources vs gem because:
I use gem for only one reason:
You need to update Javascript libs, that'll happen frequently. If you pull JS libs directly into your application, your code base will be polluted with unnecessary information when commit.
Use gems. If it does not exist, create one, it's very simple. If current gem is not updated, send a pull request or use your fork.
Here's an attempt at a pros vs. cons list.
Gemfile
with your other project dependencies.Slightly quicker and cleaner to add a Gem to your project. Compare:
Gemfile
$ bundle install
require
in application.js
require
in application.js
.Gemfile
and assets
directory.For Javascript libraries that have a well-maintained up-to-date Gem associated with it, use the Gem. For Javascript libraries that don't have a Gem, copy the lib to assets, but keep it whole. Customize the library by putting your overrides in a separate file.
This should make upgrading the library as painless as possible.
Also, in your application.js, put a comment that says where you are including the library from (Gem or asset) for clarity's sake.
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