Created
May 4, 2016 04:47
-
-
Save topher6345/3d29c66ff6eb3cdf84928a23f1772022 to your computer and use it in GitHub Desktop.
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
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