Module: Treat::Helpers::Hash::ToStruct
- Defined in:
- lib/treat/helpers/hash.rb
Overview
Mixin to allow conversion of hashes to nested structs with the keys as attributes.
Instance Method Summary collapse
-
#to_struct ⇒ Object
Converts a hash to nested structs.
Instance Method Details
#to_struct ⇒ Object
Converts a hash to nested structs.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/treat/helpers/hash.rb', line 8 def to_struct hash = self symbols = hash.keys.select { |k| !k.is_a?(Symbol) }.size return hash if symbols > 0 klass = Struct.new(*hash.keys) struct = klass.new(*hash.values) hash.each do |key, value| if value.is_a?(Hash) v = value.to_struct struct[key] = v end end; return struct end |