Frage

Looking at the rails source for ActiveModel::Validations, the HelperMethods module is both included and extended in the underlying model:

module Validations
  extend ActiveSupport::Concern

  included do
    extend ActiveModel::Callbacks
    extend ActiveModel::Translation

    extend  HelperMethods
    include HelperMethods
...

Theoretically, this allows you to not only call helper methods like validates_presence_of as class macros (as shown in all the standard examples), but to also call these helper methods directly on the model instance:

myobject.validates_presence_of :name

Where I can see this being useful is in the context of a custom validator that wants to leverage some of the existing helper methods:

class CustomValidator < ActiveModel::Validator
  def validate(record)
    record.validates_presence_of :name
    record.validates_acceptance_of :terms
    ...
  end
end

And whether or not this is encouraged behavior, it did seem to work until some changes with specific validators in Rails 4.1. So my question is if rails does not support calling these helper methods in this fashion (as instance methods on the model), why are they included in the model instead of just extended?

War es hilfreich?

Lösung

So according to this commit from roughly 4 years ago, there was indeed the intention to make these validation helpers callable from both the class and instance:

https://github.com/rails/rails/commit/9131a88bb8e82f139ec49b4057fb6065ba0a2c6a

I'm evaluating the changes made in 4.1 to see about getting these affected validation methods working again.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top