我正在尝试覆盖第三方提供的模块中的类方法。
我的目标是检查第二个参数,如果它是一个 Hash 则实例化一个新的自定义对象,否则调用原始实现:
module ThirdParty
def self.login(email, password_or_options)
if password_or_options.is_a?(Hash)
SafeSession.new(email, password_or_options['sid'], password_or_options['master_key'], password_or_options['shared_keys'], password_or_options['rsa_privk']).storage
else
super(email, password_or_options)
end
end
原始方法签名:
module ThirdParty
def self.login(email, password)
# Library doing its own stuff
end
end
目前这是失败的
ThirdParty.login('email', { test: true })
NoMethodError: super: no superclass method `login' for ThirdParty:Module
我也在使用 ActiveSupport,以防在这个框架中有解决这个问题的方法。
最佳答案
尝试:
module ThirdParty
class << self
def login_with_change(email, password_or_options)
if password_or_options.is_a?(Hash)
SafeSession.new(email, options['sid'], password_or_options['master_key'], password_or_options['shared_keys'], password_or_options['rsa_privk']).storage
else
login_without_change(email, password_or_options)
end
end
alias_method_chain :login, :change
end
end
关于ruby-on-rails - 覆盖模块类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23826857/