Class: Primalize::Single::Array

Inherits:
Object
  • Object
show all
Defined in:
lib/primalize/single.rb

Instance Method Summary collapse

Constructor Details

#initialize(types, &coercion) ⇒ Array

Returns a new instance of Array.



227
228
229
230
# File 'lib/primalize/single.rb', line 227

def initialize types, &coercion
  @types = types
  @coercion = coercion
end

Instance Method Details

#===(value) ⇒ Object



232
233
234
235
236
237
# File 'lib/primalize/single.rb', line 232

def === value
  return false unless ::Array === value
  value.all? do |item|
    @types.any? { |type| type === item }
  end
end

#coerce(array) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/primalize/single.rb', line 239

def coerce array
  if @coercion
    return @coercion.call(array)
  end

  if array.respond_to? :map
    array.map do |item|
      type = @types.find { |type| type === item }
      if type.respond_to? :coerce
        type.coerce(item)
      else
        item
      end
    end
  else
    array
  end
end

#inspectObject



258
259
260
# File 'lib/primalize/single.rb', line 258

def inspect
  "array(#{@types.map(&:inspect).join(', ')})"
end