Introducing acts_as_comparable
on April 21, 2007 @ 01:52 AM

Mark VanHolstyn and Zach Dennis kick out another ActiveRecord plugin. The previous plugin ActiveRecord::Extensions now has a smaller, helpful cousin. This plugin has been in use for over a year but not released until tonight!

“acts_as_comparable” is plugin for ActiveRecord which allows you to easily compare and determine the differences between two ActiveRecord models.

1
2
3
4
5
6
7
8
9
10
11
class Person 
  acts_as_comparable :only=>[:first_name, :last_name]
end

joe = Person.new :first_name=>"Joe", :last_name=>"Smith"
joseph = Person.new :first_name => "Joseph", :last_name=>"Smith"

joe.same?( joseph ) # => false
joe.different?( joseph ) # => true

joe.differences( joseph ) # => {:first_name=>["Joe", "Joseph"]}

The usage in the above example shows the only option, but this also works with no options, the except option and also the attrs_map option. See it’s ruby doc for more information.

Installing as a RubyGem


gem install -r acts_as_comparable

Installing as a Plugin

Installing from a version


 script/plugin install http://rails.lotswholetime.com/svn/acts_as_comparable/tags/acts_as_comparable-1.1

  1. Daniel Waite 04.21.07 / 02AM

    Pretty sweet. I’ve actually been using this technique for a while, but my solution isn’t nearly as elegant:

    I define a method that returns a hash of the attributes I consider to constitute equality, and then do something like…

    def (object) object.send(:equality_attributes) equality_attributes end

    Basically I piggy back off a hash’s ability to compare itself.

    Thanks for sharing!