Adding validations on the fly.


In some situations I'd like to extend single objects with additional
virtual attributes and validation methods for them, for example:

@foo = Foo.find(param[:id])

class << @foo
  def bar

  validates_presence_of :bar

puts @foo.valid?

However, what is puzzling is that this still returns true... Can anyone
point me at what I'm doing wrong?

Your call to validates_presence_of addss a validation on the singleton
class of @foo where it will never be executed. You'd need to add the
validation to the class Foo

  @foo.class.validates_presence_of :bar

but then it would be active for all instances of Foo in the same
process. Much better to add the validation to the class proper and
guard it with a condition

  class Foo < ActiveRecord::Base
    validates_presence_of :bar, :if => ...