Method: Hanami::Utils::Hash.deep_serialize

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

.deep_serialize(input) ⇒ ::Hash

Deep serializes given object into a ‘Hash`

Please note that the returning ‘Hash` will use symbols as keys.

Examples:

Basic Usage

require 'hanami/utils/hash'
require 'ostruct'

class Data < OpenStruct
  def to_hash
    to_h
  end
end

input = Data.new("foo" => "bar", baz => [Data.new(hello: "world")])

Hanami::Utils::Hash.deep_serialize(input)
  # => {:foo=>"bar", :baz=>[{:hello=>"world"}]}

Parameters:

  • input (#to_hash)

    the input

Returns:

  • (::Hash)

    the deep serialized hash

Since:

  • 1.1.0

[View source]

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/hanami/utils/hash.rb', line 169

def self.deep_serialize(input)
  input.to_hash.each_with_object({}) do |(key, value), output|
    output[key.to_sym] =
      case value
      when ->(h) { h.respond_to?(:to_hash) }
        deep_serialize(value)
      when Array
        value.map do |item|
          item.respond_to?(:to_hash) ? deep_serialize(item) : item
        end
      else
        value
      end
  end
end