覆盖模块类方法

时间:2014-05-23 10:28:22

标签: ruby-on-rails ruby

我正在尝试覆盖由第三方提供的模块中的类方法。

我的目标是检查第二个参数,如果它是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,以防在此框架中解决此问题。

2 个答案:

答案 0 :(得分:3)

尝试:

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

答案 1 :(得分:1)

也许这会奏效 使用alias_method为monkey_patched模块中的原始方法设置别名

 module ThirdParty
   class << self
     alias_method :login_ori, :login
   end
   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
       login_ori(email, password_or_options)
     end
   end
 end
相关问题