lib/pp-adaptive/support/coerced_array.rb in pp-adaptive-0.0.6 vs lib/pp-adaptive/support/coerced_array.rb in pp-adaptive-1.0.0

- old
+ new

@@ -1,17 +1,19 @@ module AdaptivePayments # Array that coerces all input values to a JsonModel of the given type class CoercedArray < Array + attr_accessor :type # Initialize the CoercedArray for the given type # # @param [Class<JsonModel>] type # the JsonModel descendant to coerce to - def initialize(type) + def self.for_type(type) raise ArgumentError, "The type in a CoercedArray must be a JsonModel" unless type <= JsonModel - super() - @type = type + arr = CoercedArray.new + arr.type = type + arr end # Append the given value to the Array # The value may be a Hash to coerce, or a valid JsonModel # @@ -32,21 +34,25 @@ # @param [Array] other # another Array to concatenate with # # @return CoercedArray def +(other) - raise ArgumentError, "Cannot union #{other.class} with #{self.class}<#{@type}>" unless other.kind_of?(Array) - super(CoercedArray.new(@type).concat(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 # Concatenate another Array with this one and modify the Array in place # # @param [Array] other # another Array to concatenate with # # @return CoercedArray 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) }) + 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 end end