Class: AdaptivePayments::CoercedArray

Inherits:
Array
  • Object
show all
Defined in:
lib/pp-adaptive/support/coerced_array.rb

Overview

Array that coerces all input values to a JsonModel of the given type

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#typeObject

Returns the value of attribute type.



4
5
6
# File 'lib/pp-adaptive/support/coerced_array.rb', line 4

def type
  @type
end

Class Method Details

.for_type(type) ⇒ Object

Initialize the CoercedArray for the given type

Parameters:

  • type (Class<JsonModel>)

    the JsonModel descendant to coerce to

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
# File 'lib/pp-adaptive/support/coerced_array.rb', line 9

def self.for_type(type)
  raise ArgumentError, "The type in a CoercedArray must be a JsonModel" unless type <= JsonModel

  arr = CoercedArray.new
  arr.type = type
  arr
end

Instance Method Details

#+(other) ⇒ Object

Concatenate another Array with this one and return the result as a new Array All items in other will be coerced to the correct type

Parameters:

  • other (Array)

    another Array to concatenate with

Returns:

  • CoercedArray

Raises:

  • (ArgumentError)


38
39
40
41
42
43
# File 'lib/pp-adaptive/support/coerced_array.rb', line 38

def +(other)
  raise ArgumentError, "Cannot union #{other.class} with #{self.class}<#{type}>" unless other.kind_of?(Array)
  result = CoercedArray.new(super(CoercedArray.for_type(type).concat(other)))
  result.type = type
  result
end

#concat(other) ⇒ Object

Concatenate another Array with this one and modify the Array in place

Parameters:

  • other (Array)

    another Array to concatenate with

Returns:

  • CoercedArray

Raises:

  • (ArgumentError)


51
52
53
54
55
56
# File 'lib/pp-adaptive/support/coerced_array.rb', line 51

def concat(other)
  raise ArgumentError, "Cannot append #{other.class} to #{self.class}<#{type}>" unless other.kind_of?(Array)
  result = CoercedArray.new(super(other.inject(CoercedArray.for_type(type)) { |ary, v| ary.push(v) }))
  result.type = type
  result
end

#push(object) ⇒ Object Also known as: <<

Append the given value to the Array The value may be a Hash to coerce, or a valid JsonModel

Parameters:

  • object (Hash, JsonModel)

    the object to append

Returns:

  • CoercedArray



24
25
26
27
# File 'lib/pp-adaptive/support/coerced_array.rb', line 24

def push(object)
  object = @type.new(object) unless object.kind_of?(@type)
  super
end