Opto/Model
Uses Opto as the engine to add validatable attributes and build nestable models from Ruby objects.
Installation
Add this line to your application's Gemfile:
gem 'opto-model'
And then execute:
$ bundle
Or install it yourself as:
$ gem install opto-model
Why?
Why not use Virtus or dry-types or ModelAttribute or X? Why not indeed. While Opto based attributes bring some handy benefits, such as the resolvers, you will probably find the alternatives a lot more full featured and sophisticated.
Usage
See Opto README for attribute definition syntax reference.
Defining models
require 'opto-model'
class Name
include Opto.model
attribute :first_name, :string
attribute :last_name, :string
end
class Person
include Opto.model
has_one :name, Name, required: true
has_many :friends, Person
attribute :age, :integer, min: 18
end
Interacting with models (yes please)
Create an instance
guy = Person.new
gal = Person.new(age: 20, name: { first_name: 'Elaine' }, friends: [guy])
Validating
guy.valid?
=> false
guy.errors
=> { :name => { :presence => "Child missing: 'name'" }, :age => { :presence => "Required value missing" } }
Relations
Using another model:
guy.name
=> nil
guy.name = Name.new(first_name: 'Guybrush', last_name: 'Threepwood')
guy.name.first_name
=> "Guybrush"
Using new
:
guy.name.new(first_name: 'Guybrush', last_name: 'Threepwood')
Using a hash:
guy.name = {first_name: 'Guybrush', last_name: 'Threepwood'}
Using nested attributes:
guy = Person.new(age: 18, name: { first_name: "Guybrush", last_name: "Threepwood" }, friends: [ { last_name: 'LeChuck' } ])
Also validates and collects errors for children:
guy.valid?
=> false
guy.errors
=> { :friends => { 0 => { :first_name => { :presence => "Required value missing" } } } }
..unless told not to:
guy.valid?(false)
=> true
guy.errors(false)
=> {}
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/kontena/opto-model.