How do Ruby Gems work?

Learn how Ruby Gems work and where the code is stored, how methods are defined and when/where/why does Rails load the code.

One of the things that makes working with Rails so nice is that for any common programming need---authorization, site administration, ecommerce, you name it---someone smarter than you has likely coded up the solution for your problem and packaged it up in the form of a gem.

You can certainly add gems to your Gemfile and take full advantage of their usefulness without truly understanding how they work, but have you ever been curious how it all gets wired up?

Here we'll take a closer look at Ryan Bates' CanCan authorization gem and answer the following questions (which, if asked more broadly, could apply to any gem):

  1. Where does the code for CanCan get stored?

  2. Where is the can? method defined?

  3. When/where/how does Rails load the code for CanCan?

First, I have CanCan in my Gemfile and I do a bundle install:

# Gemfile
gem "cancan", "~> 1.6.10"```

$ bundle install

With Bundler it's actually really easy to see where any particular gem lives. Just use bundle show:

$ bundle show cancan
/Users/jasonswett/.rvm/gems/ruby-2.0.0-p0/gems/cancan-1.6.10

That takes care of question #1. Now where is can? defined?

$ cd /Users/jasonswett/.rvm/gems/ruby-2.0.0-p0/gems/cancan-1.6.10
$ grep -r 'def can?' *
lib/cancan/ability.rb: def can?(action, subject, *extra_args)
lib/cancan/controller_additions.rb: def can?(*args)

It looks like there are actually two different can? functions. The one we're interested in is in lib/cancan/ability.rb.

# lib/cancan/ability.rb

def can?(action, subject, *extra_args)
match = relevant_rules_for_match(action, subject).detect do |rule|
rule.matches_conditions?(action, subject, extra_args)
end
match ? match.base_behavior : false
end

As far as what's actually happening here, your guess is as good as mine, but that's not the important part. The takeaway here is that if you're bumping up against some problem with a gem, you're now equpped to dig into the gem's code to try to figure out what's going on.

Now that we know where a gem's code is kept and how to get into it, how does Rails know about a gem, and when does it load a gem's code?

This is covered in a certain section of the Rails initialization documentation. Here's the relevant part:

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. If the Gemfile exists, bundler/setup is then required.

This happens early on in the initialization process: the second step, to be exact. This makes sense since if your project depends on a certain gem, who knows where you might reference it. Better load it as early as possible so its code can be used anywhere.

What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Starr Horne

    Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.

    More articles by Starr Horne
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like: