0

I was wondering what the differences are between using a Ruby gem to include a JavaScript library into a Rails project versus including the JavaScript file yourself.

I do know that you can lock down a version of the js library using bundler or alternatively, update all of your js libraries through bundler with one command instead of manually coping and pasting js files into your project. How much overhead does the Rails::Engine class add and is this the only way to get the asset files from a gem available in a Rails app? Are there any other notable differences that shows which way is "the best" way to include these libraries?

Aaron
  • 13,349
  • 11
  • 66
  • 105

2 Answers2

0

The Rails::Engine class is overkill (even if harmless, as it wouldn't have a lot of running code) for a gem that provides just assets. With a Railtie is more than enough. The difference is negligible in any case.

With an external gem you can save storing the assets in your project.

For instance, the angular-rails gem provides some off-line code to generate things, it doesn't affect your app.

On the other side, you have to wait the gem maintainer to update it with new versions of the library when needed.

rewritten
  • 16,280
  • 2
  • 47
  • 50
0

Great post from olaf_from_norweden on reddit with the answer:

Let's walk through what the Sass port of the Twitter Bootstrap gem actually does:

https://github.com/thomas-mcdonald/bootstrap-sass/blob/master/lib/bootstrap-sass.rb

When the bootstrap gem is evaluated on Rails initialization (when you boot up the server), it uses require to load various parts of itself depending on the environment.

If the Compass Sass framework gem is loaded, it tells Compass the Rails asset folder paths to use.

If you're using a Rails version with the asset pipeline, it loads an empty Rails::Engine.

Engines are just Rails apps that you can mount onto other Rails apps. When Rails encounters an engine during initialization, it looks up the paths that the engine specifies to load relevant files.

In this case, the gemspec tells Rails during initialization about the .scss/.png/.js files in its included vendor directory.

In development mode, Rails will recompile these assets on every request along with the other assets in the main application.

In production, the bootstrap gem isn't even loaded because it goes in the :assets group of your Gemfile.

Hope that makes sense. Not the best or most salient explanation. And even if the gem was loaded in production, Rails doesn't go hunting for assets directories unless it's compiling assets. So it doesn't even matter.

Community
  • 1
  • 1
Aaron
  • 13,349
  • 11
  • 66
  • 105