Yet another attributes on steroids gem.
Heavily inspired by Virtus and Values which both are great projects.
The purpose of this project is to have a small & simple codebase and minimum number of features. For a more complex solution I strongly recommend Virtus which I'm happily using in production.
nil
's flying aroundattr_reader
and attr_writer
. Can be easily overwrittenLet's write a Person
class:
require 'attrs'
class Person < Attrs(:name, :age)
private
def default_name
"Anonymous"
end
def age=(new_age)
super(new_age.to_i)
end
end
person = Person.new(name: 'John Doe', age: '26')
with this code we can:
person.attributes # => {:name => "John Doe", :age => 26}
Person.attribute_names # => [:name, :age]
person == {:name => "John Doe", :age => 26} # => true
and more! See: https://github.com/wojtekmach/attrs/blob/master/test/attrs_test.rb
Notice in previous example we added custom age=
writer to coerce argument to integer.
One of my favourite features of Virtus is attribute coercion, and you can use it here too. In fact it's using the same library that was extracted out from Virtus: https://github.com/solnic/coercible
gem install coercible
require 'attrs/coercible'
class Person < Attrs(name: String, age: Integer)
end
or, simply:
Person = Attrs(name: String, age: Integer)
(note, using 2nd style you won't be able to use super
when overwriting methods)
Add this line to your application's Gemfile:
gem 'attrs'
And then execute:
$ bundle
Or install it yourself as:
$ gem install attrs
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)