We’re Ruby on Rails development agency that has done many tailor-made web solutions for startups and enterprises. We create websites and web applications for logistics, e-commerce, marketing, fintech, education, healthcare, residential cleaning and other industries you can think about. We also contribute to the open-source and recently created Attr-filters gem for filtering object attributes. Today we are going to share with you our experience.
What Attr-filters is made for?
Attr-filters are a lightweight gem for filtering PORO (Plain Old Ruby Objects) attributes with zero dependencies. They bring simple DSL for adding filters to your PORO attributes and are easy to integrate with Rails validation.
What we’ve done here?
We created a small gem that introduces a simple DSL of adding filters for the attributes of an object. This gem has no dependencies and is intuitive to use. It also integrates naturally with ActiveRecord.
If we want to clear the first_name field from spaces and remove duplicate spaces, then we need to add before_validation callback and code will look like this:
But what if we need to filter many fields according to different filtering criteria? For these purposes, we can use attr_filters gem. It will simplify this process:
How it is different from the analogs?
We created this gem when we created one of our projects. We noticed that we were doing the same routine work for many forms and decided to extract it in the gem.
This our gem has analogs like attribute-filters, but it has such advantages as:
- lack of dependencies;
- the ability to use out of context Rails;
- more flexibility in the settings of each filter;
- easily expands with new filters;
- the ability to use not only Form Object in any objects;
- more intuitive DSL
This gem was created to filter these forms before validating them. Therefore, the main place of application is the use in Form Object. But it is very easy to integrate them into any PORO (Plain Old Ruby Objects) such as Service Object:
How long it took to develop it?
The development of this gem took me only a few days. This is from bootstrapping a default gem skeleton to using this finished product in a real project. Considering the writing of automatic tests, the solution to the problem of the absence of dependencies (in gem there is no dependency on Rails but you need to be able to work with ActiveModel callbacks). Setup CI, taking into account the support of all versions of Ruby above 2.4 and also Rails 4.2 and higher.
Here you can explore how the gem works by yourself.
Anton Holovko, Syndicode’s Team Lead of Dnipro Office and RoR Developer.
p.s. Subscribe to Syndicode newsletter to get all the interesting news right to your mailbox!
Or just hire a professional team of Ruby/Rails developers who are always aware of the latest trends and know how to use all the latest tools!