Aktibibo is a simple Ruby gem that makes your model activatable. It allows an ActiveRecord model to be declared as “activatable” thus providing scopes for querying and filtering objects. Of course, the module adds convenience methods for setting an instance as active, inactive or deactivated. As an additional feature, it also saves the activation and deactivation dates because it uses datetime DB columns instead of just simple boolean flags.
Link to gem: https://rubygems.org/gems/aktibibo
So the codes…
Disclaimer: I created this for fun, practice and future convenience when I need an “activatable” module. This is basic.
Anyway, you can check the source code here: https://github.com/katpadi/aktibibo
I just need to explain some parts of the code because my blog is telling me that I am below the minimum recommended 300 words.
First things first… the extend ActiveSupport::Concern
means we’re creating a mixin.
The module ClassMethods
block basically defines Class methods in itself. For example, in my code above, it adds the declaration of a model to make it “activatable” and it includes the scopes. This function tells the model class that it can query objects by using the defined scopes. Note that you can do a lot of things here other than scopes. But since this is just a simple gem, it’s just doing that.
Going back to the code, everything that is defined within the module and out of the module ClassMethods
block will be instance methods. They will be executed within the context of the instance the model that is including the module.
Le setup
- Create the necessary columns using a migration:
rails generate migration add_activated_at_to_foo activated_at:datetime de
activated_at:datetime
- Define that your model is “activatable” by adding the ff in your model:
Usage
Let’s say that an instance foo
is available.
Methods
Non-bang methods will just return nil (gracefully) if an already active instance is activated. Same goes for deactivate.
Methods with a bang!
Bang methods, on the other hand, will raise AktibiboError
if activated while active or deactivated while deactivated/inactive.
Raising “AktibiboError
” is weird. I know.
Boolean methods
Scopes
Datetimes
Link to gem: https://rubygems.org/gems/aktibibo