Sha256: f9f241f7b536b48eeb97e3446eb9508dcae06c659f93834f2bed03e6c6a3ce04
Contents?: true
Size: 1.02 KB
Versions: 1
Compression:
Stored size: 1.02 KB
Contents
require "deep_struct/version" # Mixin module for converter. module DeepStruct # Converts a Hash to a Struct. If the Hash has nested Hash objects, they are converted # to Struct as well. # output = deep_struct({x: 1, y: {z: 2}}) # output.x #=> 1 # output.y.z #=> 2 # # @param [Hash] input # @return [Struct] def deep_struct(input) output = input.clone levels = output.keys.map { |key| [key, output] } levels.each do |key, context| if context[key].is_a?(Hash) # overwrite the shared reference with input by a new reference context[key] = context[key].clone subset = context[key] subset.each { |subkey, subvalue| levels.push([subkey, subset]) if subvalue.is_a?(Hash) } end end levels.reverse_each do |k, context| if context[k].is_a?(Hash) klass = Struct.new(*context[k].keys, keyword_init: true) context[k] = klass.new(context[k]) end end klass = Struct.new(*output.keys, keyword_init: true) klass.new(output) end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
deep_hash_struct-0.1.7 | lib/deep_struct.rb |