Never been to DZone Snippets before?

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

Add a to_conditions method to ActiveRecord::Base for converting models to finder :conditions hash. (See related posts)

// 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)

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts