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
24
# 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}",
    default_method: "#{name}_default"
  }
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



109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/schema/model.rb', line 109

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])
      next if value.nil? && !opts[:include_nils]
      next if opts[:select_filter] && !opts[:select_filter].call(field_name, value, field_options)
      next if opts[:reject_filter] && opts[:reject_filter].call(field_name, value, field_options)

      memo[field_name] = value
    end
  end
end

#not_set?Boolean

Returns:

  • (Boolean)


131
132
133
134
135
# File 'lib/schema/model.rb', line 131

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

#parsing_errorsObject



127
128
129
# File 'lib/schema/model.rb', line 127

def parsing_errors
  @parsing_errors ||= Errors.new
end

#to_hashObject Also known as: to_h



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

def to_hash
  as_json(include_nils: true)
end

#update_attributes(data) ⇒ Object



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

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