Project

opto-model

0.0
No commit activity in last 3 years
No release in over 3 years
Uses Opto to add attributes to Ruby objects
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.12
~> 10.0
~> 3.0

Runtime

~> 1.7
 Project Readme

Opto/Model

Build Status

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.