views:

287

answers:

1

I have an object which whether validation happens or not should depend on a boolean, or in another way, validation is optional. I haven't found a clean way to do it. What I'm currently doing is this (disclaimer: you cannot unsee, leave this page if you are too sensitive):

def valid?
  if perform_validation
    super
  else
    super        # Call valid? so that callbacks get called and things like encrypting passwords and generating salt in before_validation actually happen
    errors.clear # but then clear the errors
    true         # and claim ourselves to be valid. This is super hacky!
  end
end

Any better ways?

Before you point to the :if argument of many validations, this is for a user model which is using authlogic so it has a lot of validation rules. You can stop reading here if you belive me.

If you don't, authlogic already sets some :ifs like:

:if => :email_changed?

which I have to turn into

:if => Proc.new {|user| user.email_changed? and user.perform_validation}

and in some other cases, since I'm also using authlogic-oid (OpenID) I just don't have control over the :if, authlogic-oid sets it in a way I cannot change it (in time) without further monkey patching. So I have to override seemingly unrelated functions, catch exceptions if a method doesn't exist, etc. The previous hacky solution if the best of my two attempts.

+1  A: 

I really don't understand your question at all. If you want to save the object without performing any validations then just call save(false).

Azeem.Butt
I don't want to save the object, I want to disable validations. The object may or may not get saved as a side effect of saving an associated object and I don't know when or where. I never mention saving the object.
J. Pablo Fernández
You never mention a lot of things or use appropriate grammar in describing the things that you do mention, so it's pretty difficult to tell what you're talking about. Your object's validations are not going to magically run themselves at any time other than when it is being saved. If you find that is not the case, then explain why.
Azeem.Butt
Validators are run when you run valid? or when you save an object that has this new object as associated, or when an object that associated has a validates_association. If you find grammar errors, be my guest to correct them, english is not my native language and I still make mistakes.
J. Pablo Fernández
I can't fix them when I have no idea what you're even trying to say.
Azeem.Butt