ActiveEntity
An extension for Active Model to encourage implementing entity. It's like Virtus gem but more simple and on Active Model way.
Installation
Add this line to your application's Gemfile:
gem 'active_entity'
And then execute:
$ bundle
Or install it yourself as:
$ gem install active_entity
Synopsis
# = Define model attributes with accessor and define identities =
class Message
include ActiveModel::Model
include ActiveEntity::Accessor
include ActiveEntity::Identity
attribute :title
attribute :body
identity_attribute :title
validates :title, presence: true, length: { maximum: 255 }
validates :body, presence: true
end
= Message.new(title: 'A README of ActiveEntity')
expect(.valid?).to be_falsy
expect(.errors).to be_a(ActiveModel::Errors)
= Message.new(title: 'A README of ActiveEntity', body: 'No contents!')
expect(.valid?).to be_truthy
expect(.attributes).to eq({ "title" => "A README of ActiveEntity", "body" => "No contents!" })
another_messsage = Message.new(title: 'A README of ActiveEntity', body: '')
expect().to eq(another_messsage)
# = Coercion =
class Person
include ActiveModel::Model
include ActiveEntity::Accessor
include ActiveEntity::Coercion
attribute :name, type: String
attribute :age, type: Integer
end
alice = Person.new(name: 'Alice', age: '1')
expect(alice.name).to eq('Alice')
expect(alice.age).to eq(1)
# = Typecasting =
class Recipe
include ActiveModel::Model
include ActiveEntity::Accessor
include ActiveEntity::Typecasting
attribute :title, type: String
attribute :steps, type: Integer
attribute :likes, type: Integer
end
waffle = Recipe.new(title: 'Waffle', steps: '12', likes: 'abc')
expect { waffle.cast! }.to raise_error(ActiveEntity::CastError)
expect(waffle.title).to eq('Waffle')
expect(waffle.steps).to eq('12') #=> rollbacks casted value on error
expect(waffle.likes).to eq('abc')
TODOs
to_param
helper.- Default value support.
- Custom coercion with object.
- Value object.
- Docs for typecasting custom procedures.
Contributing
- Fork it ( https://github.com/taiki45/active_entity/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request