Skip to content

Instantly share code, notes, and snippets.

@hkraji
Last active December 28, 2015 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkraji/7526519 to your computer and use it in GitHub Desktop.
Save hkraji/7526519 to your computer and use it in GitHub Desktop.
Hash to OpenStruct nested convert
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