Module: SchemaModel::ClassMethods

Defined in:
lib/utils/schema_model.rb

Instance Method Summary collapse

Instance Method Details

#schema(_name, opts = {}) ⇒ Object

Dynamically configures accessors, dirty tracking, validation, and serialization methods given definition in opts

Parameters:

  • _name (Object)
    • name of schema

  • opts (Hash) (defaults to: {})
    • See below

    class AwesomeClass

    schema :my_schema,
      id: {
       type: Numeric,             # value will be checked using is_a?
       valid: -> (v) { v > 0 },   # value will be validated by calling this
       schema: [ChildClass]       # single or collection recursive checks
       doc: 'Id, number greater than 1'  # documentation string
      }
    

    end

    a = AwesomeClass.new(id: 1) a.valid? => true a.errors => {}



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/utils/schema_model.rb', line 29

def schema(_name, opts = {})
  define_method(:definition) { opts }

  opts.each do |k, definition|
    # Reader
    attr_reader k

    # Writer
    define_writer! k, definition
  end
end