Class: NestedStruct::Coercer

Inherits:
Object
  • Object
show all
Defined in:
lib/nested_struct/coercer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression) ⇒ Coercer

Returns a new instance of Coercer.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/nested_struct/coercer.rb', line 5

def initialize(expression)
  if expression.is_a?(Class)
    @type = :single
    @target = expression
  elsif expression.is_a?(Array)
    raise Errors::InvalidCoercerExpression if expression.size != 1
    @type = :multiple
    @target = expression.first
  else
    raise Errors::InvalidCoercerExpression
  end

  raise Errors::InvalidCoercerTarget if !valid_target?
end

Instance Attribute Details

#targetObject (readonly)

Returns the value of attribute target.



3
4
5
# File 'lib/nested_struct/coercer.rb', line 3

def target
  @target
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/nested_struct/coercer.rb', line 3

def type
  @type
end

Instance Method Details

#coerce(value) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/nested_struct/coercer.rb', line 20

def coerce(value)
  if multiple?
    raise Errors::InvalidCoercerValue if !value.is_a?(Array)
    value.map { |e| single_coercion(e) }
  else
    single_coercion(value)
  end
end

#multiple?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/nested_struct/coercer.rb', line 29

def multiple?
  type == :multiple
end