Class: Objectifier::MapValue

Inherits:
Object
  • Object
show all
Defined in:
lib/objectifier/map_value.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope = "", &block) ⇒ MapValue

Returns a new instance of MapValue.



7
8
9
10
11
# File 'lib/objectifier/map_value.rb', line 7

def initialize(scope = "", &block)
  @scope = scope.to_s
  @rules = Hash.new
  instance_eval &block
end

Instance Attribute Details

#rulesObject (readonly)

Returns the value of attribute rules.



5
6
7
# File 'lib/objectifier/map_value.rb', line 5

def rules
  @rules
end

Instance Method Details

#call(parameters) ⇒ Object

examine parameters and return a hash of massaged data or an error results



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/objectifier/map_value.rb', line 39

def call(parameters)

  if @scope.length > 0
    parameters = parameters.fetch(
      @scope,
      parameters.fetch(
        @scope.to_s,
        {}))
  end

  ok, errors = @rules.values.map do |rule|
    rule.call(parameters)
  end.partition do |result|
    result.success?
  end

  if errors.empty?
    values = ok.select(&:value?)

    if values.empty?
      SuccessResult.new(@scope)
    else
      ValueResult.new(
        @scope,
        Hash[values.map { |v| [ v.name, v.value ] }])
    end
  else
    errors.reduce(ErrorResult.new) { |total, err| total.merge(err) }.scope(@scope)
  end
end

#item(name, args) ⇒ Object



23
24
25
26
# File 'lib/objectifier/map_value.rb', line 23

def item(name, args)
  @rules[name.to_s] = ScalarValue.new(name, args)
  true
end

#items(name, args) ⇒ Object



28
29
30
31
# File 'lib/objectifier/map_value.rb', line 28

def items(name, args)
  @rules[name.to_s] = ArrayValue.new(name, args)
  true
end

#map(name, &block) ⇒ Object



33
34
35
36
# File 'lib/objectifier/map_value.rb', line 33

def map(name, &block)
  @rules[name.to_s] = MapValue.new(name, &block)
  true
end

#nameObject



13
14
15
# File 'lib/objectifier/map_value.rb', line 13

def name
  @scope
end

#required?Boolean

Returns:

  • (Boolean)


17
18
19
20
21
# File 'lib/objectifier/map_value.rb', line 17

def required?
  @rules.values.reduce(false) do |req, rule|
    req || rule.required?
  end
end