Skip to content

Instantly share code, notes, and snippets.

@wflanagan
Created October 29, 2018 13:04
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 wflanagan/515b04b3448d9494df5fc386ce3b75c3 to your computer and use it in GitHub Desktop.
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
# 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