-
-
Save wflanagan/515b04b3448d9494df5fc386ce3b75c3 to your computer and use it in GitHub Desktop.
If a class exists, then use it. If not, then create the class as a child class of OpenStruct
This file contains 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
# ActiveSupport is loaded | |
items = [ | |
{type: 'post', a: 'a', b: 'b', c: 'c'}, | |
{type: 'resource', b: 'c', c: 'd', d: 'b'} | |
{type: 'resource', c: 'b', b: 'c', a: 'a'} | |
] | |
def transform_hash(hsh) | |
if hsh.key?(:type) | |
singular_name = hsh[:type].singularize.titleize | |
klass_name = "WordpressApiRuby::#{singular_name}" | |
if Object.const_defined?("WordpressApiRuby::#{singular_name}") | |
klass = klass_name.constantize | |
else | |
klass = Object.const_set klass_name, Class.new(OpenStruct) | |
end | |
klass.new(hsh) | |
else | |
OpenStruct.new(hsh) | |
end | |
rescue => e | |
# #<NameError: wrong constant name WordpressApiRuby::Resource> | |
binding.pry | |
end | |
items.map do |item| | |
transform_hash(item) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment