Skip to content

Instantly share code, notes, and snippets.

@topher6345
Created May 4, 2016 04:47
Show Gist options
  • Save topher6345/3d29c66ff6eb3cdf84928a23f1772022 to your computer and use it in GitHub Desktop.
Save topher6345/3d29c66ff6eb3cdf84928a23f1772022 to your computer and use it in GitHub Desktop.
def traverse instance
attributes = instance.attributes
klass = instance.class
associations = klass.reflect_on_all_associations
return attributes unless associations
associations.map(&:name).each do |key|
result = instance.send key
value = nil
value = if result
association = klass.reflect_on_association key
case association.macro
when :has_many then result.map { |o| call o }
when :has_one then call result
end
end
attributes.merge! key.to_s => value
end
attributes
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment