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 Method Summary collapse

Constructor Details

#initialize(type) ⇒ CoercedArray

Initialize the CoercedArray for the given type

Parameters:

  • type (Class<JsonModel>)

    the JsonModel descendant to coerce to

Raises:

  • (ArgumentError)


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

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

  super()
  @type = type
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)


36
37
38
39
# File 'lib/pp-adaptive/support/coerced_array.rb', line 36

def +(other)
  raise ArgumentError, "Cannot union #{other.class} with #{self.class}<#{@type}>" unless other.kind_of?(Array)
  super(CoercedArray.new(@type).concat(other))
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)


47
48
49
50
# File 'lib/pp-adaptive/support/coerced_array.rb', line 47

def concat(other)
  raise ArgumentError, "Cannot append #{other.class} to #{self.class}<#{@type}>" unless other.kind_of?(Array)
  super(other.inject(CoercedArray.new(@type)) { |ary, v| ary.push(v) })
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



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

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