If you extract some of your Rails code into a gem, and test the gem separately, this will guarantee that the gem cannot depend on the rest of your application. This is a Good Thing: if everything can depend on everything else, you end up with a hideous tangled mess.

And it’s dead easy. First, assuming you are in your app’s root directory, let’s create the gem (using -t to include RSpec tests):

mkdir gems
cd gems
bundle gem my_gem -t
cd my_gem

First (of course), we’re going to write a test and check that it fails. This goes in spec/my_gem_spec.rb. Here’s the code:

it 'should do something useful' do
  expect(Class.new.extend(MyGem).wibble).to eq("Wobble")
end

Check it fails:

rspec
# Failed examples:
#
# rspec ./spec/my_gem_spec.rb:8 # MyGem should do something useful

Then the code itself goes in lib/my_gem.rb. (You don’t need to put all the code in there, of course; just put some require statements at the top, linking to the other files.) I’ve added a method to mine:

module MyGem
  # Your code goes here...
  def wibble
    "Wobble"
  end
end

Check rspec works … and that’s it: you now have a gem!

The next task is to include my_gem in the Rails app. First add to the app’s Gemfile:

gem 'my_gem', path: 'gems'

Then run bundle in the app’s root directory. (It will give some warning messages about the gemspec, but don’t worry.) Then you can use the gem in your app. For example:

class MyModel < ActiveRecord::Base
  include MyGem
end

Job done. Now MyModel has a #wibble method. Just what you needed:

MyModel.new.wibble #=> "Wobble"


comments powered by Disqus