Class: Surrealist::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/surrealist/builder.rb

Overview

A class that builds a hash from the schema and type-checks the values.

Defined Under Namespace

Classes: Schema

Instance Method Summary collapse

Constructor Details

#initialize(carrier, schema, instance) ⇒ Builder

Returns a new instance of Builder.

Parameters:

  • carrier (Carrier)

    instance of Surrealist::Carrier

  • schema (Hash)

    the schema defined in the object’s class.

  • instance (Object)

    the instance of the object which methods from the schema are called on.



13
14
15
16
17
# File 'lib/surrealist/builder.rb', line 13

def initialize(carrier, schema, instance)
  @carrier = carrier
  @schema = schema
  @instance = instance
end

Instance Method Details

#call(schema = @schema, instance = @instance) ⇒ Hash

A method that goes recursively through the schema hash, defines the values and type-checks them.

Parameters:

  • schema (Hash) (defaults to: @schema)

    the schema defined in the object’s class.

  • instance (Object) (defaults to: @instance)

    the instance of the object which methods from the schema are called on.

Returns:

  • (Hash)

    a hash that will be dumped into JSON.

Raises:

  • Surrealist::UndefinedMethodError if a key defined in the schema does not have a corresponding method on the object.



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

def call(schema = @schema, instance = @instance)
  schema.each do |schema_key, schema_value|
    if schema_value.is_a?(Hash)
      check_for_ar(schema, instance, schema_key, schema_value)
    else
      ValueAssigner.assign(Schema.new(schema_key, schema_value),
                           instance) { |coerced_value| schema[schema_key] = coerced_value }
    end
  end
rescue NoMethodError => e
  Surrealist::ExceptionRaiser.raise_invalid_key!(e)
end