SingletonValidations =================== David A. Black Ruby Power and Light, LLC Version 1.0.0 July 4, 2008 This plugin makes it possible to use the ActiveRecord class-level validation methods at the instance level. You can call methods like validates_size_of and validates_format_of directly on your Thing objects. These "singleton" validations will override the class ones, if those are present. The idea for this plugin came from an IRC question by 'mickey', about how to get class-style validations on a singleton basis. I haven't found mickey again. But I appreciate his or her getting me thinking about this. Example ======= Here's a simple "thing" model, followed by some examples of how to use the validates_* class methods on individual objects of the Thing class. things table: name string priority integer description string class Thing < ActiveRecord::Base validates_size_of :name, :minimum => 3 validates_numericality_of :priority end t = Thing.new(:name => 'abc', :priority => 10) p t.save # true t.validates_size_of :name, :minimum => 5 p t.save # false p t.errors.entries # name is too short, minimum 5 t.priority = 10.1 t.validates_numericality_of :priority, :only_integer => true p t.valid? # false p t.errors.entries # name too short; priority is not a number t.priority = 10 t.name = "abcde" p t.valid? # true t.validates_presence_of :description p t.valid? # false; no description t.description = "abc" p t.valid? # true # Just to make sure that the singleton validations didn't # propagate to the class: try a new Thing object. t = Thing.new p t.valid? # false p t.errors.entries How it works ============ The plugin works by overriding the run_callbacks method in the ActiveSupport::Callbacks module, so that it checks not only the object's class but also its singleton class for callback chains. The callback chains get inserted into the singleton class of an object courtesy of ActiveRecord#method_missing, which has been hooked with alias_method_chain so that when you call a method that starts with "validates_", it checks to see whether that method is a class method and if it is, it runs it in the singleton class context. License and (lack of) warranty ============================== MIT License (see file).