Module: Finitio::HashBasedType

Included in:
MultiTupleType, TupleType
Defined in:
lib/finitio/type/hash_based_type.rb,
lib/finitio/generation/hash_based_type.rb

Instance Method Summary collapse

Instance Method Details

#dress(value, handler = DressHelper.new) ⇒ Object

Convert ‘value` (supposed to be Hash) to a Tuple, by checking attributes and applying `dress` on them in turn. Raise an error if any attribute is missing or unrecognized, as well as if any sub transformation fails.



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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/finitio/type/hash_based_type.rb', line 24

def dress(value, handler = DressHelper.new)
  handler.failed!(self, value) unless looks_a_tuple?(value)

  # Check for missing attributes
  unless (missing = missing_attrs(value, true)).empty?
    handler.fail!("Missing attribute `#{missing.first}`")
  end

  # Uped values, i.e. tuple under construction
  uped = {}

  # Check for extra attributes
  extra = extra_attrs(value, true)
  case extra_type = heading.extra_type
  when NilClass
    handler.fail!("Unrecognized attribute `#{extra.first}`") unless extra.empty?
  when ANY_TYPE
    # ok, nothing to do
  else
    extra.each do |attr|
      handler.deeper(attr) do
        attr_value = value.fetch(attr){|k| value.fetch(attr.to_sym) }
        uped[attr.to_sym] = extra_type.dress(attr_value, handler)
      end
    end
  end

  # Up each attribute in turn now. Fail on missing ones.
  heading.each do |attribute|
    present = true
    val = attribute.fetch_on(value){ present = false }
    next unless present
    handler.deeper(attribute.name) do
      uped[attribute.name] = attribute.type.dress(val, handler)
    end
  end

  uped
end

#generate_data(generator, world = nil) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/finitio/generation/hash_based_type.rb', line 4

def generate_data(generator, world = nil)
  tuple = {}
  heading.each do |a|
    if a.required or generator.flip_coin
      tuple[a.name.to_sym] = generator.call(a.type, world)
    end
  end
  tuple
end

#include?(value) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
# File 'lib/finitio/type/hash_based_type.rb', line 12

def include?(value)
  value.is_a?(Hash) &&
  heading.all?{|a|
    value.has_key?(a.name) ? a.type.include?(value[a.name]) : true
  } &&
  !missing_attr?(value) &&
  valid_extra_attrs?(value)
end

#representatorObject



4
5
6
7
8
9
10
# File 'lib/finitio/type/hash_based_type.rb', line 4

def representator
  rep = {}
  heading.each do |attr|
    rep[attr.name] = rep[attr.type.representator]
  end
  rep
end