Module: OpenStruct::FromHash

Included in:
OpenStruct
Defined in:
lib/llm/core_ext/ostruct.rb

Instance Method Summary collapse

Instance Method Details

#from_hash(obj) ⇒ OpenStruct

Returns An OpenStruct object initialized by visiting obj with recursion.

Examples:

obj = OpenStruct.from_hash(person: {name: 'John'})
obj.person.name  # => 'John'
obj.person.class # => OpenStruct

Parameters:

  • obj (Hash, Array)

    A Hash object

Returns:

  • (OpenStruct)

    An OpenStruct object initialized by visiting obj with recursion



15
16
17
18
19
20
21
22
23
24
# File 'lib/llm/core_ext/ostruct.rb', line 15

def from_hash(obj)
  case obj
  when self then from_hash(obj.to_h)
  when Array then obj.map { |v| from_hash(v) }
  else
    visited = {}
    obj.each { visited[_1] = walk(_2) }
    new(visited)
  end
end