Hello my dear readers!
Today is something I would call quite an event in my life. I've made a Ruby gem of my own! It's called Classy Filter, and it's a library for performing filtering in an object-oriented, class-based, configurable fashion.
Here's a quick little example of usage.
class MyFilter < ClassyFilter::Base
filter_field :first_name # (1)
filter_field :last_name_prefix, attribute: :last_name, \
predicate: :starts_with_i # (2)
filter_field :dob_after, attribute: :date_of_birth, \
predicate: :gteq, coercion: :integer # (3)
filter_field :rough_trust, attribute: :trust_level,
predicate: :gt_10x, coercion: :integer # (4)
predicate :gt_10x,
->(dataset, attr, input) { dataset.where { |r| Sequel[attr] > input } } # (5)
end
Line ➊ shows us how to define a very basic filter. This definition lets our
filter accept the first_name
parameter and perform simple filtering by
equality or inclusion.
Line ➋ shows us how to define a filter with a custom predicate and parameter
name. Our filter will accept the last_name_prefix
parameter and filter by the
last_name
column, using ILIKE
to do it.
Line ➌ shows us how to define a filter not just with a custom predicate, but
also with a coercion. Before performing the filtering, our filter will attempt
to coerce the dob_after
parameter into an Integer.
Line ➎ shows us a custom predicate (that's used on the line ➍). A
predicate is defined using the ClassyFilter::Base.predicate
method that
accepts the predicate name and a proc that receives the dataset, the attribute
name and the parameter value.
Using the created filter is fairly easy. Just pass the filtering parameters
into the filter constructor and #call
it with the dataset, like this:
ds = DB[:people] # Our dataset
MyFilter.new(params).call(ds)
Currently it only supports Sequel, but hopefully by the time 1.0 comes out, I'll make it less platform-depended and maybe make an ActiveRecord backend!
If you're interested in the gem, feel free to see its GitLab repo! And if you have any bugs or questions, feel free to post an issue!