我试图理解为什么我的班级方法无法识别。以下是我的代码:
wiki_patch.rb
require_dependency 'wiki_content'
module WikiRecipientPatch
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
alias_method_chain :recipients, :send_wiki_mail
end
end
end
module InstanceMethods
def self.set_mail_checker(mail)
@mail_checker = mail
end
end
Rails.configuration.to_prepare do
WikiContent.send(:include, WikiRecipientPatch)
end
controller.rb
WikiContent.set_mail_checker(params[:mail_checker_wiki])
我收到此错误:
NoMethodError (undefined method `set_mail_checker' for #<Class:0x4876560>):
知道它为什么会发生以及它的解决方案是什么?
答案 0 :(得分:1)
你的成语有点不对。
ClassMethods
/ InstanceMethods
模块应该嵌套在“main”模块中(在本例中为WikiRecipientPatch
)。 您正在包含实例方法,但期望以某种方式出现类方法?当然你的意思是extend ClassMethods
,不是吗?
module WikiRecipientPatch
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def set_mail_checker(mail)
'mail checker'
end
end
end
class WikiContent; end
WikiContent.send(:include, WikiRecipientPatch)
WikiContent.set_mail_checker('whatever') # => "mail checker"