ruby-on-rails - 覆盖模块类方法

标签 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,以防在这个框架中有解决这个问题的方法。

最佳答案

尝试:

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/

相关文章:

ruby-on-rails - Rails 非表格下拉列表

ruby-on-rails - Rails html.erb 文件类型,<% %> 和 <%= %> 的区别

ruby-on-rails - "assigns"在 Ruby on Rails 中有什么作用?

ruby-on-rails - 升级到ActiveRecord::ConnectionNotEstablished错误

ruby-on-rails - 具有固定页面链接数的Kaminari分页控件

ruby-on-rails - 使用 Ruby on Rails 清理用户输入

ruby-on-rails - 如何搭建rubygems镜像服务器?

ruby-on-rails - 使用 RubyXL 编写 xlsx 文件需要很长时间且包含大量单元格

ruby-on-rails - 错误 : RVM Ruby not used, 首先运行 `rvm use 1.9.1`

ruby-on-rails - 从零开始学习 Ruby 单元测试