bigpotato
bigpotato

Reputation: 27497

Rails + Gems (in general): How do gems work?

I've been using Rails for a while and have always used gems in my gemfile, but I never really understood how the functionality of gems that I install actually become available. Say I use the has_permalinks gem (http://haspermalink.org/). It provides a .generate_permalink! method for my Model. Where does this method get defined? How come just I can use this method all of a sudden just by installing the gem? Is there some sort of include/require/load to initialize the gem's code so that it becomes accessible to the rest of the application? Also, where is this code stored when I install the gem?

Upvotes: 10

Views: 797

Answers (1)

Jason Swett
Jason Swett

Reputation: 45074

I answered your questions separately, and out of order, but I think it actually might make it easier to understand the answers in this order.

Also, where is this code stored when I install the gem?

If you're using Bundler, you can do bundle show has_permalink and it will show you where that gem is installed. Here's an example of me doing it with the pg gem:

✗ bundle show pg
/Users/jasonswett/.rvm/gems/ruby-1.9.2-p320@jason/gems/pg-0.11.0

Where does this method get defined?

If you do the bundle show thing, it returns a path - the method is defined somewhere in there. (You can use grep -r 'def generate_permalink' /gem/path to find exactly where if you want.)

How come just I can use this method all of a sudden just by installing the gem? Is there some sort of include/require/load to initialize the gem's code so that it becomes accessible to the rest of the application?

Look at this part of the doc about the Rails initialization process: http://guides.rubyonrails.org/initialization.html#config-boot-rb

In a standard Rails application, there’s a Gemfile which declares all dependencies of the application. config/boot.rb sets ENV["BUNDLE_GEMFILE"] to the location of this file, then requires Bundler and calls Bundler.setup which adds the dependencies of the application (including all the Rails parts) to the load path, making them available for the application to load.

It looks like, fairly early on in the process, Rails looks at your Gemfile and loads all your gems via Bundler. So there's your include.

Upvotes: 15

Related Questions