Writing My First RubyGem - CanBe

I started working on a personal project in Ruby on Rails, that probably will not see the light of day. I had an Active Record model that could have different attributes depending on the type of record that it was. In Rails, there are different ways to create your models to handle data in this manner. For example, you could have a different model for each type of record. However, this creates some challenges when querying the data. It would be difficult to query data to return a result set that would include different types of models.

You could also use ActiveRecord Single table inheritence to implement the functionality that met my requirements. That’s when my data modeling and DBA experience kicked in. Using STI would result in database rows with many null values in them. This didn’t feel right to me.

That’s why I wrote the CanBe gem. With the CanBe gem, you can declaratively define the possible types for any given instance of your model. Initially, it just provided many helper methods to ensure consistency. Then I enhanced it to allow for different attributes depending on type of model instance that you are accessing. To accomplish this, I used polymorphic associations to connect up different models that represent the specific attributes required for the instance type.

As of version 0.2.1 of the CanBe gem, I have implemented most of the functionality that I wanted to include. There are still a few more tweaks that I would like to make. I am hoping that other developers will find the functionality useful. If you want to see functionality, that is not currently included, feel free to contact me or submit a pull request. Contributions are always welcome and appreciated.

Writing my first gem has been a great experience! It furthered my knowledge of the Ruby language and how to integrate with Ruby on Rails, specifically ActiveRecord. I was able to apply TDD techniques to ensure the gem didn’t break as I added new functionality. I worked with Travis to ensure that my code was integrated properly when changes were made.

I hope that others find the CanBe gem useful for their projects!

Comments
« I'm going to write a book! Shipping vs. Learning »

Comments