Rasti::Model
Domain models with typed attributes
Installation
Add this line to your application's Gemfile:
gem 'rasti-model'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rasti-model
Usage
Basic models
class Point < Rasti::Model
attribute :x
attribute :y
end
point = Point.new x: 1, y: 2
point.x # => 1
point.y # => 2
Typed models
T = Rasti::Types
class TypedPoint < Rasti::Model
attribute :x, T::Integer
attribute :y, T::Integer
end
point = TypedPoint.new x: '1', y: '2'
point.x # => 1
point.y # => 2
Inline definition
Point = Rasti::Model[:x, :y]
TypedPoint = Rasti::Model[x: T::Integer, y: T::Integer]
Serialization and deserialization
City = Rasti::Model[name: T::String]
Country = Rasti::Model[name: T::String, cities: T::Array[T::Model[City]]]
attributes = {
name: 'Argentina',
cities: [
{name: 'Buenos Aires'},
{name: 'Córdoba'},
{name: 'Rosario'}
]
}
country = Country.new attributes
country.name # => 'Argentina'
country.cities # => [City[name: "Buenos Aires"], City[name: "Córdoba"], City[name: "Rosario"]]
country.to_h # => attributes
Error handling
TypedPoint = Rasti::Model[x: T::Integer, y: T::Integer]
point = TypedPoint.new x: true
point.x # => Rasti::Types::CastError: Invalid cast: true -> Rasti::Types::Integer
point.y # => Rasti::Model::NotAssignedAttributeError: Not assigned attribute y
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/gabynaiman/rasti-model.
License
The gem is available as open source under the terms of the MIT License.