0

我试图路径 ActiveRecord 模型验证 -

require_dependency "issue"
module IssuePath
  def self.included(base) # :nodoc:
    base.send(:include, InstanceMethods)

    base.class_eval do
      alias_method :strict_validate_issue, :validate_issue
      alias_method :validate_issue, :unstrict_validate_issue 
    end
  end

  module ClassMethods   
  end

  module InstanceMethods
    def strict_validate_issue
      if !due_date
          errors.add :due_date, :due_date_empty
      end
      unstrict_validate_issue
    end
  end
end

Issue.send :include, IssuePath

但它抛出了一个错误 NameError: undefined method unstrict_validate_issue' for classIssue (call 'Issue.connection' to建立连接)'。

4

1 回答 1

0

而不是strict_validate_issue定义unstrict_validate_issue方法并strict_validate_issue在其中调用。

require_dependency "issue"
module IssuePath
  def self.included(base) # :nodoc:
    base.send(:include, InstanceMethods)

    base.class_eval do
      alias_method :strict_validate_issue, :validate_issue
      alias_method :validate_issue, :unstrict_validate_issue
    end
  end

  module ClassMethods
  end

  module InstanceMethods
    def unstrict_validate_issue
      if due_date.blank?
        errors.add :due_date, :due_date_empty
      end
      strict_validate_issue
    end
  end
end

Issue.send :include, IssuePath

你甚至可以让它更短:

require_dependency "issue"
module IssuePath
  extend ActiveSupport::Concern

  included do
    alias_method :strict_validate_issue, :validate_issue
    alias_method :validate_issue, :unstrict_validate_issue
  end

  def unstrict_validate_issue
    if due_date.blank?
      errors.add :due_date, :due_date_empty
    end
    strict_validate_issue
  end
end

Issue.send :include, IssuePath
于 2020-01-10T11:04:11.970 回答