DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Chu has posted 12 posts at DZone. View Full User Profile

Add A To_conditions Method To ActiveRecord::Base For Converting Models To Finder :conditions Hash.

03.26.2007
| 5873 views |
  • submit to reddit
        // Mixes in a to_conditions method to ActiveRecord::Base. Converts the attributes of an AR object to a
// ActiveRecord::Base#find :conditions hash. Useful for comparing AR objects, especially when looking for
// duplicates.
// E.g.
//   
//   if not Post.find(:all, :conditions => my_post.conditions).empty?
//     puts "Duplicate found"
//   end

module Bezurk #:nodoc:
  module ActiveRecord #:nodoc:
    module Extensions
      def to_conditions
        attributes.inject({}) do |hash, (name, value)|
          hash.merge(name.intern => value)
        end
      end
      alias :to_conditions_hash :to_conditions
    end
  end
end

ActiveRecord::Base.send(:include, Bezurk::ActiveRecord::Extensions)