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):
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:
Check it fails:
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:
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
:
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:
Job done. Now MyModel
has a #wibble
method. Just what you needed: