Class: Parameters::Types::Array

Inherits:
Object show all
Defined in:
lib/parameters/types/array.rb

Direct Known Subclasses

Set

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Object

===, to_ruby

Methods inherited from Type

#<, #<=, ===, to_ruby

Constructor Details

#initialize(element_type) ⇒ Array

Initializes the Array type.

Parameters:

  • element_type (Type, nil)

    Optional type for the elements of the Array.



16
17
18
# File 'lib/parameters/types/array.rb', line 16

def initialize(element_type)
  @element_type = element_type
end

Instance Attribute Details

#element_typeObject (readonly)

The type to coerce all Array elements with



8
9
10
# File 'lib/parameters/types/array.rb', line 8

def element_type
  @element_type
end

Class Method Details

.coerce(value) ⇒ ::Array

Coerces a value into an Array.

Parameters:

  • value (#to_a, ::Object)

    The value to coerce.

Returns:

  • (::Array)

    The coerced Array.



41
42
43
44
45
46
47
48
49
# File 'lib/parameters/types/array.rb', line 41

def self.coerce(value)
  if value.respond_to?(:to_a)
    value.to_a
  elsif value.respond_to?(:to_ary)
    value.to_ary
  else
    [value]
  end
end

.element_typeObject

The element type of the Array type.

Returns:

  • (Object)

    The default element type.

Since:

  • 0.4.0



28
29
30
# File 'lib/parameters/types/array.rb', line 28

def self.element_type
  Object
end

Instance Method Details

#==(other) ⇒ ::Boolean

Compares the instance type with another type.

Parameters:

  • other (Array, Type)

    The other type to compare against.

Returns:

  • (::Boolean)

    Specificies whether the instance type has the same element type as the other Array instance type.

Since:

  • 0.4.0



73
74
75
# File 'lib/parameters/types/array.rb', line 73

def ==(other)
  super(other) && (@element_type == other.element_type)
end

#===(value) ⇒ ::Boolean

Determines if the value is an Array.

Parameters:

  • value (::Object)

    The value to inspect.

Returns:

  • (::Boolean)


85
86
87
88
89
# File 'lib/parameters/types/array.rb', line 85

def ===(value)
  (self.class === value) && value.all? { |element|
    @element_type === element
  }
end

#coerce(value) ⇒ ::Array

Coerces a value into an Array, and coerces the elements of the Array.

Parameters:

  • value (#to_a, ::Object)

    The value to coerce.

Returns:

  • (::Array)

    The coerced Array.

See Also:



102
103
104
105
106
107
# File 'lib/parameters/types/array.rb', line 102

def coerce(value)
  array = super(value)
  array.map! { |element| @element_type.coerce(element) }

  return array
end

#to_rubyArray<Class>

The Ruby Type for the Array Type instance.

Returns:

  • (Array<Class>)

    A singleton Array containing the element-type.



57
58
59
# File 'lib/parameters/types/array.rb', line 57

def to_ruby
  self.class.to_ruby[@element_type.to_ruby]
end