Skip to content

Instantly share code, notes, and snippets.

@renancarvalhoo
Forked from dkln/ar_to_hash.rb
Last active December 19, 2016 16:05
Show Gist options
  • Save renancarvalhoo/67053b46ed1ab51539417961c9d1a185 to your computer and use it in GitHub Desktop.
Save renancarvalhoo/67053b46ed1ab51539417961c9d1a185 to your computer and use it in GitHub Desktop.
Convert any Activerecord to a hash with all it's related objects
class Serializer < Struct.new(:object)
#w.association_cache.keys.include?
def to_hash
@hash ||= hash_object(object)
end
private
def hash_object(object)
hash = {}
hash.merge! object.attributes
each_association_collection(object) do |association, association_name, item|
path << object
if assocation_has_collection?(association)
hash[association_name] ||= []
hash[association_name] << hash_object(item)
else
hash[association_name] = hash_object(item)
end
path.pop
end
hash
end
def path
@path ||= []
end
def assocation_has_collection?(association)
[:has_many, :has_and_belongs_to_many].include? association.macro
end
def have_visited_object?(object)
self.object == object || path.include?(object)
end
def each_association_collection(object)
object.class.reflect_on_all_associations.each do |association|
association_name = association.name.to_s
association_collection(object, association_name).each do |item|
yield(association, association_name, item) unless have_visited_object?(item)
end
end
end
def association_collection(object, association_name)
object.send(association_name).to_a
end
def visited_objects
@visited_objects ||= []
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment