Skip to content

Instantly share code, notes, and snippets.

@MacksMind
Created March 26, 2013 13:52
Show Gist options
  • Save MacksMind/5245523 to your computer and use it in GitHub Desktop.
Save MacksMind/5245523 to your computer and use it in GitHub Desktop.
Sometimes I've needed a 'deep compare' for ActiveRecord objects. This method returns a Hash containing the objects attributes plus the attributes from the first layer of relationships. After using #except to exclude attributes that should change, I can assert_equal to compare.
class ActiveSupport::TestCase
def attr_tree(obj)
tree = obj.attributes.except("id")
obj.class.reflections.each do |refl_name,refl|
refl_key = refl_name.to_s
case refl.macro
when :belongs_to, :has_one
tree[refl_key] = (o = obj.send(refl_name)) && o.attributes
when :has_many, :has_and_belongs_to_many
tree[refl_key] = []
obj.send(refl_name).each{|o| tree[refl_key] << o.attributes.except("id")}
else
raise "Unhandled reflection #{refl.macro} :#{refl_name}"
end
end
tree
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment