模型类的未定义方法,我不想通过alias_method进行修改



我试图路径活动记录模型验证 -

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:未定义的方法unstrict_validate_issue' for class问题(调用"Issue.connection"以建立连接("。

而不是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

相关内容

  • 没有找到相关文章

最新更新