Last active
December 28, 2015 16:09
-
-
Save hkraji/7526519 to your computer and use it in GitHub Desktop.
Hash to OpenStruct nested convert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ostruct' | |
def self.convert_data(elements) | |
results = [] | |
if elements.is_a?(Array) | |
elements.each do |el| | |
results << deep_convert(el) | |
end | |
else | |
results = deep_convert(elements) | |
end | |
# depending on the input response will be array of | |
# open struct object or single open struct object | |
results | |
end | |
def self.deep_convert(data) | |
return data unless data.is_a?(Hash) | |
element = OpenStruct.new(data) | |
get_methods = get_mutators_only(element) | |
get_methods.each do |g_meth| | |
child = element.send(g_meth) | |
if child.is_a?(Array) | |
results = convert_data(child) | |
element.send("#{g_meth}=", [*results]) | |
end | |
end | |
element | |
end | |
# | |
# Returns only getters for OpenStruct object | |
# | |
def self.get_mutators_only(element) | |
# only instance methods and exclude methods which have '=' (setter mutators) | |
(element.methods - OpenStruct.instance_methods).select { |meth| !meth.to_s.include?('=')} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment