Method: Hanami::Utils::Kernel.Hash

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

.Hash(arg) ⇒ Hash

Coerces the argument to be a Hash.

Examples:

Basic Usage

require 'hanami/utils/kernel'

Hanami::Utils::Kernel.Hash(nil)                 # => {}
Hanami::Utils::Kernel.Hash({a: 1})              # => { :a => 1 }
Hanami::Utils::Kernel.Hash([[:a, 1]])           # => { :a => 1 }
Hanami::Utils::Kernel.Hash(Set.new([[:a, 1]]))  # => { :a => 1 }

Hash Interface

require 'hanami/utils/kernel'

Room = Class.new do
  def initialize(*args)
    @args = args
  end

  def to_h
    Hash[*@args]
  end
end

Record = Class.new do
  def initialize(attributes = {})
    @attributes = attributes
  end

  def to_hash
    @attributes
  end
end

room = Room.new(:key, 123456)
Hanami::Utils::Kernel.Hash(room)        # => { :key => 123456 }

record = Record.new(name: 'L')
Hanami::Utils::Kernel.Hash(record)      # => { :name => "L" }

Unchecked Exceptions

require 'hanami/utils/kernel'

input = BasicObject.new
Hanami::Utils::Kernel.Hash(input) # => TypeError

Parameters:

  • arg (Object)

    the input

Returns:

  • (Hash)

    the result of the coercion

Raises:

  • (TypeError)

    if arg can’t be coerced

See Also:

Since:

  • 0.1.1

[View source]

214
215
216
217
218
219
220
221
222
# File 'lib/hanami/utils/kernel.rb', line 214

def self.Hash(arg)
  if arg.respond_to?(:to_h)
    arg.to_h
  else
    super
  end
rescue NoMethodError
  raise TypeError.new "can't convert #{inspect_type_error(arg)}into Hash"
end