Method: Hanami::Utils::Kernel.Array

Defined in:
lib/hanami/utils/kernel.rb

.Array(arg) ⇒ Array

Coerces the argument to be an Array.

It’s similar to Ruby’s Kernel.Array, but it applies further transformations:

* flatten
* compact
* uniq

Examples:

Basic Usage

require 'hanami/utils/kernel'

Hanami::Utils::Kernel.Array(nil)              # => []
Hanami::Utils::Kernel.Array(true)             # => [true]
Hanami::Utils::Kernel.Array(false)            # => [false]
Hanami::Utils::Kernel.Array(1)                # => [1]
Hanami::Utils::Kernel.Array([1])              # => [1]
Hanami::Utils::Kernel.Array([1, [2]])         # => [1,2]
Hanami::Utils::Kernel.Array([1, [2, nil]])    # => [1,2]
Hanami::Utils::Kernel.Array([1, [2, nil, 1]]) # => [1,2]

Array Interface

require 'hanami/utils/kernel'

ResultSet = Struct.new(:records) do
  def to_a
    records.to_a.sort
  end
end

Response = Struct.new(:status, :headers, :body) do
  def to_ary
    [status, headers, body]
  end
end

set = ResultSet.new([2,1,3])
Hanami::Utils::Kernel.Array(set)              # => [1,2,3]

response = Response.new(200, {}, 'hello')
Hanami::Utils::Kernel.Array(response)         # => [200, {}, "hello"]

Parameters:

  • arg (Object)

    the input

Returns:

  • (Array)

    the result of the coercion

See Also:

Since:

  • 0.1.1

[View source]

95
96
97
98
99
100
101
# File 'lib/hanami/utils/kernel.rb', line 95

def self.Array(arg)
  super.dup.tap do |a|
    a.flatten!
    a.compact!
    a.uniq!
  end
end