default_attributes

Define and initialize attributes for PORO.


License
MIT
Install
gem install default_attributes -v 0.2.0

Documentation

Build Status Code Climate

DefaultAttributes

Yet another gem to define PORO attributes. Inspired by ShallowAttributes.

Installation

Add this line to your application's Gemfile:

gem 'default_attributes'

And then execute:

$ bundle

Or install it yourself as:

$ gem install default_attributes

Usage

class User
  include DefaultAttributes
  
  attributes(:name) { self&.to_s&.capitalize || 'Alexey' }
  attributes :id, :group_id, &:to_i
  attributes :slug, &->(val) { val || "#{id}_#{name}" }
end

User.new
=> #<User: @_default_attributes={:name=>"Alexey", :id=>0, :group_id=>0, :slug=>"0_Alexey"}>
user = User.new(name: 'ivan', id: '1')
=> #<User: @_default_attributes={:name=>"Ivan", :id=>1, :group_id=>0, :slug=>"1_Ivan"}>
user.name
=> "Ivan"
user.id = 2
=> 2

Private setter/getter

class User
  attributes :password, private: true
end
user = User.new(password: 'qwer')
user.password
=> NoMethodError: private method `password' called for ..

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/belousovAV/default_attributes.

License

The gem is available as open source under the terms of the MIT License.