Let me introduce you to my new library called Yukata. It is a light weight Ruby attribute library that is configurable and extendable.
Virtus has been a huge inspiration for this library. I enjoyed the DSL it offered, while allowing me to have a quick way to make data objects.
Here is an example on how to utilize Yukata:
1 2 3 4 5 6
#attribute method is straight forward with its meaning. It is dynamically
creating both getter and setter methods for the object. It can be thought of as
attr_accessor but with a few extra features. It provides a fast way to
discover what data type can be expected for that attribute.
When using Yukata, the the initializer expects a hash to be provided or a class
that behaves like a
1 2 3 4 5
Yukata will take the hash and assign the values to their respective attribute keys. If a setter method is defined, then a corresponding value can be passed as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
:coerce => false is passed, then Yukata will not attempt to coerce that
attribute and leave it as is. This can be handy if a custom coercion is desired
for the specific model. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Now, remember just because there is access directly to instance variables does not mean it is okay to abuse them. With great power comes great responsibility, this means I am not responsible for your mistakes.
Setting Attribute Defaults
Sometimes the objects need default values if it is not set. Defaults are lazily loaded. They will only be set once the getter method is called.
1 2 3 4
Registering Custom Coercions
This library only comes with basic coercers. I tried to make as little assumptions about the data coming in as I could. I believe that the consumer of the library should be the one who defines the coercions.
If the value can not be coerced, it is simply passed through and left alone.
1 2 3
Optional Readers and Writers
When declaring an attribute, both the reader and writer can be skipped. There is a use case where this would be handy.
1 2 3 4 5 6 7 8 9 10 11
This is a bit contrived, but it demonstrates the following:
- The expected return data type for
- Custom coercer is defined.
- The attribute will be included when
#attributesis called on
:writer => false is provided, there would be no need to include
:coerce => false since the coercion only takes place when the value is being
set on the object.
I wrote this library becaues I wanted to see how Virtus accomplished this task and how I could go about doing it differently. This is a highly configurable library that can be used to put your fat models on a diet.