Today, I wrote my first Ruby on Rails gem. It was a very simple refactoring of our code that I undertook when I needed to add the same functionality to a new model and I decided to do it as a gem instead of keeping it within our project. I wanted to see how it worked and this is what I ended up with. You can follow the Rails Guide, but it didn’t cover everything I wanted to do.
Create a repository for your gem.
Create a skeleton gem
Rails 3.1 ships with a rails plugin new command which creates a skeleton for developing any kind of Rails extension with the ability to run integration tests using a dummy Rails application.
I used this to create a skeleton for my plugin:
This creates a skeleton gem with a dummy rails application you can use for testing your gem.
Switch to rspec
- Add rspec as a development dependency in your gemspec
- Bundle Install
- Convert from test-unit to rspec
- Modify spec_helper.rb with code taken from test_helper.rb
- Run the tests
- Commit the skeleton gem to source control
Author your gem
At this point, you have a skeleton gem that you can use to write your code. The gem I wrote added some behavior to ActiveRecord models, so I started out by generating some models in the dummy rails application located in spec/dummy and using test-driven development to build my gem.