module Schema::Model

Schema::Model adds schema building methods to a class

Public Class Methods

default_attribute_options(name, type) click to toggle source
# 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) click to toggle source
# 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

Public Instance Methods

as_json(opts = {}) click to toggle source
# 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?() click to toggle source
# 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_errors() click to toggle source
# File lib/schema/model.rb, line 127
def parsing_errors
  @parsing_errors ||= Errors.new
end
to_h()
Alias for: to_hash
to_hash() click to toggle source
# File lib/schema/model.rb, line 122
def to_hash
  as_json(include_nils: true)
end
Also aliased as: to_h
update_attributes(data) click to toggle source
# 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

Private Instance Methods

get_schema(data) click to toggle source
# File lib/schema/model.rb, line 139
def get_schema(data)
  data.each_key do |key|
    break unless key.is_a?(Symbol)

    return self.class.schema
  end
  self.class.schema_with_string_keys
end
update_associations(schema, data) click to toggle source
# File lib/schema/model.rb, line 161
def update_associations(schema, data)
  data.each do |key, value|
    next unless schema.key?(key)
    next unless schema[key][:association]

    public_send(schema[key][:setter], value)
  end
end
update_model_attributes(schema, data) click to toggle source
# File lib/schema/model.rb, line 148
def update_model_attributes(schema, data)
  data.each do |key, value|
    unless schema.key?(key)
      parsing_errors.add(key, ::Schema::ParsingErrors::UNKNOWN_ATTRIBUTE)
      next
    end

    next if schema[key][:association]

    public_send(schema[key][:setter], value)
  end
end