In modern versions of ActiveRecord you can define any number of before_validation
handlers using a simpl开发者_如何学Goe declaration:
class MyModel < ActiveRecord::Base
before_validation :do_something
before_validation :do_something_else
end
Using Sequel it looks like the only way you can do this is similar to the older ActiveRecord method:
class MyModel < Sequel::Model
def before_validation
super
do_something
do_something_else
end
end
Is there a plugin that adds the simplified declarations, or is that just how it is? The Sequel documentation doesn't paint a very clear picture. There is no MyModel.before_validation
class method defined.
Update: As the answers below indicate, this behavior is not present by default. I've made a Sequel::Model plugin that fixes this called sequel_simple_callbacks
As Brian Campbell mentioned, you can use the validation_class_methods
plugin. It's not recommended, but it is supported. The validation_helpers
plugin gives you similar helpers that the validation_class_methods
plugin gives you, for use as instance methods inside the validate
method.
Writing validations as instance methods is a better approach, IMO, which is why Sequel encourages it. Validations are inherently an instance level activity, not a class level activity. With the class level validations, handling things like conditional validation has to have special syntax (like :if=>proc{}
), where you can just use normal conditional ruby statements in the instance method (such as if
, else
, case
, etc.).
Obviously, if you are coming from ActiveRecord, it's a different approach. Sequel does not attempt to clone ActiveRecord's behavior, though the two libraries operate similarly in some respects.
It looks like Sequel has a plugin, validation_class_methods
, which provide a class-method based interface for adding validations. According to the validation documentation it is intended only for legacy compatibility, but if you prefer that interface, it should be fine to use it.
精彩评论