Module: Schema::Model

Defined in:
lib/schema/model.rb

Overview

Schema::Model adds schema building methods to a class

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_attribute_options(name, type) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/schema/model.rb', line 14

def self.default_attribute_options(name, type)
  {
    key: name.to_s.freeze,
    name: name,
    type: type,
    getter: name.to_s.freeze,
    setter: "#{name}=",
    instance_variable: "@#{name}"
  }
end

.included(base) ⇒ Object



8
9
10
11
12
# File 'lib/schema/model.rb', line 8

def self.included(base)
  base.extend InheritanceHelper::Methods
  base.send(:include, Schema::Parsers::Common)
  base.extend ClassMethods
end

Instance Method Details

#as_json(opts = {}) ⇒ Object



102
103
104
105
106
107
108
109
# File 'lib/schema/model.rb', line 102

def as_json(opts = {})
  self.class.schema.each_with_object({}) do |(field_name, field_options), memo|
    unless field_options[:alias_of]
      value = public_send(field_options[:getter])
      memo[field_name] = value if !value.nil? || opts[:include_nils]
    end
  end
end

#not_set? ⇒ Boolean

Returns:

  • (Boolean)


120
121
122
123
124
# File 'lib/schema/model.rb', line 120

def not_set?
  self.class.schema.values.all? do |field_options|
    !instance_variable_defined?(field_options[:instance_variable])
  end
end

#parsing_errors ⇒ Object



116
117
118
# File 'lib/schema/model.rb', line 116

def parsing_errors
  @parsing_errors ||= Errors.new
end

#to_hash ⇒ Object Also known as: to_h



111
112
113
# File 'lib/schema/model.rb', line 111

def to_hash
  as_json(include_nils: true)
end

#update_attributes(data) ⇒ Object



95
96
97
98
99
100
# File 'lib/schema/model.rb', line 95

def update_attributes(data)
  schema = get_schema(data)
  update_model_attributes(schema, data)
  update_associations(schema, data)
  self
end