Class: Camille::Types::Object

Inherits:
BasicType show all
Defined in:
lib/camille/types/object.rb

Defined Under Namespace

Classes: ArgumentError

Instance Attribute Summary collapse

Attributes inherited from BasicType

#fingerprint

Instance Method Summary collapse

Methods inherited from BasicType

&, #&, #[], [], directly_instantiable?, inherited, instance, #transform, #|, |

Constructor Details

#initialize(fields) ⇒ Object

Returns a new instance of Object.



7
8
9
10
11
# File 'lib/camille/types/object.rb', line 7

def initialize fields
  @optional_keys = []
  @fields = normalize_fields fields
  @fingerprint = generate_fingerprint
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



5
6
7
# File 'lib/camille/types/object.rb', line 5

def fields
  @fields
end

#optional_keysObject (readonly)

Returns the value of attribute optional_keys.



5
6
7
# File 'lib/camille/types/object.rb', line 5

def optional_keys
  @optional_keys
end

Instance Method Details

#check(value) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/camille/types/object.rb', line 13

def check value
  if value.is_a? Hash
    keys = (@fields.keys + value.keys).uniq
    keys_to_check, keys_to_skip = keys.partition{|key| @fields[key]}

    results = keys_to_check.map do |key|
      type = @fields[key]
      if @optional_keys.include?(key) && value[key].nil?
        nil
      else
        [key, type.check(value[key])]
      end
    end.compact

    errors = results.map do |key, result|
      if result.type_error?
        [key.to_s, result]
      else
        nil
      end
    end.compact

    skipped_pairs = keys_to_skip.map do |key|
      [key, value[key]]
    end

    if errors.empty?
      object = Camille::ObjectHash[results.map{|key, checked| [key, checked.value]}.concat(skipped_pairs).to_h]
      Camille::Checked.new(fingerprint, object)
    else
      Camille::TypeError.new(**errors.to_h)
    end
  else
    Camille::TypeError.new("Expected hash, got #{value.inspect}.")
  end
end

#literalObject



50
51
52
# File 'lib/camille/types/object.rb', line 50

def literal
  "{#{@fields.map{|k,v| "#{literal_key k}: #{v.literal}"}.join(', ')}}"
end