In the Ruby world, mixins are very popular. In fact, I’ve created a number of basic mixins (or concerns) in Rails projects and so it came to a point where I wanted to try converting it to a gem. Why? Because why not? Well, just for the experience.
Anyway, my first RubyGem is called Sorty Sorter. It sorts AR collection when given a set of parameters that will be validated against the whitelisted attributes in the model.
Given an ActiveRecord::Relation collection and some arguments, the gem should:
- define the model attributes (and their defaults) for sorting
- whitelist the only sortable columns
- alias the column name so it won’t be exposed to the outside world
- extend ActiveRecord::Relation and add a convenience method to sort according to arguments passed
I already have the mixin and other classes that will do the goals I mentioned above.
To convert it to a gem, I browsed the http://guides.rubygems.org/make-your-own-gem. Of course. And then I came up with the hows.
I want to be able to define something in the model on the class level. This hypothetical (at that point when I was thinking) method will take a hash argument so I can configure options. Anyway, I need to extend ActiveSupport::Concern and define class method and then mix in that method.
Module#include is private so one way to “hack” it is the code above. It mixes in the sort_with method in the model.
And then, I would add to ActiveRecord::Relation exstensions so I can use method
sorty_sort within a collection.
After doing these things, user can define
sort_with in the model and AR collections will have a