Do you remember my previous post about Yandex::Webmaster gem? In the end of the post there was an example of typed attributes in plain Ruby class. I said that we plan to extract this functionality from Yandex::Webmaster into a separate gem and we’ve done it today!
But stop! Have ever looked in Virtus code? Or why should load ActiveModel as a dependency while using ActiveAttr??? Or why Virtus redefines
#attributes= method in my model without even asking me? To much questions for libraries that just should provide functionality to define attributes.
That is why we in JetRockets decided that we should create our own solution. It should be clear, easy to use, extend and work without any dependencies.
Meet Attrio! Attrio is not as monstrous as Virtus, does not have any external dependencies like ActiveAttr, but still rather powerful and configurable.
To use Attrio include it into your class and then call
1 2 3 4 5 6 7 8 9 10
Now instance of your
User model has the following methods:
Attrio supports several build in types like:
Symbol. But actually every Ruby class can be used as a type in Attrio. If it has a
typecasted? method then value for the attribute will be created with this methods, if not – then common
new method will be called.
Attrio supports default values for the attributes:
1 2 3 4 5 6 7 8 9 10 11 12
By default Attrio defines
#attributes accessor which contains a
Hash with attributes names as keys and instances of
Attrio::Attribute as values.
1 2 3 4 5 6
Accessor name can be easily overridden by passing
:as option to
1 2 3 4 5 6 7 8 9
Attrio is well tested and works under 1.9.2, 1.9.3, 2.0.0, Rubinius and JRuby and we will continue to support all these interpreters and future releases.
The first gem that will use Attrio will be Yandex::Webmaster, after it Yandex::Metrika will also be rewritten. Also we are glad to say, that Attrio is the first gem, that was developed under our company account on GitHub and I hope that it is not the last one.