Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping hash maps to class instances

Looking for gem or at least idea how to approach this problem, the ones I have are not exactly elegant :)

Idea is simple I would like to map hashes such as:

{ :name => 'foo',
  :age  => 15,
  :job => {
        :job_name => 'bar',
        :position => 'something'
    ...
  }
}

To objects of classes (with flat member structure) or Struct such as:

class Person {
  @name
  @age
  @job_name
  ...
}

Thanks all.

like image 577
Haris Krajina Avatar asked Jan 25 '26 12:01

Haris Krajina


1 Answers

Assuming that you can be certain sub-entry keys won't conflict with containing entry keys, here's some code that should work...

require 'ostruct'

def flatten_hash(hash)
  hash = hash.dup
  hash.entries.each do |k,v|
    next unless v.is_a?(Hash)
    v = flatten_hash(v)
    hash.delete(k)
    hash.merge! v
  end
  hash
end

def flat_struct_from_hash(hash)
  hash = flatten_hash(hash)
  OpenStruct.new(hash)
end
like image 140
Steve Jorgensen Avatar answered Jan 28 '26 05:01

Steve Jorgensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!