ruby-on-rails - 覆盖 gem 的关注点 - Rails

标签 ruby-on-rails overriding

我正在尝试修改一个 gem(准确地说是设计 token 身份验证)以满足我的需要。为此,我想覆盖关注点 SetUserByToken 中的某些函数。

问题是我该如何覆盖它?

我不想更改 gem 文件。有没有一种简单/标准的方法可以做到这一点?

最佳答案

请记住,Rails 中的“关注点”只是一个模块,带有来自 ActiveSupport::Concern 的一些程序员便利。 .

当您在类中包含模块时,类本身定义的方法将优先于包含的模块。

module Greeter
  def hello
    "hello world"
  end
end

class LeetSpeaker
  include Greeter
  def hello 
    super.tr("e", "3").tr("o", "0")
  end
end

LeetSpeaker.new.hello # => "h3ll0 w0rld"

因此,您可以非常简单地在 ApplicationController 中重新定义所需的方法,甚至可以编写您自己的模块,而无需猴子修补库:

module Greeter
  extend ActiveSupport::Concern

  def hello
    "hello world"
  end

  class_methods do
     def foo
       "bar"
     end
  end
end

module BetterGreeter
  extend ActiveSupport::Concern

  def hello
    super.titlecase
  end

  # we can override class methods as well.
  class_methods do
     def foo
       "baz"
     end
  end
end

class Person
  include Greeter # the order of inclusion matters
  include BetterGreeter
end

Person.new.hello # => "Hello World"
Person.foo # => "baz"

参见 Monkey patching: the good, the bad and the ugly为了很好地解释为什么将自定义代码覆盖在框架或库之上而不是在运行时修改库组件通常更好。

关于ruby-on-rails - 覆盖 gem 的关注点 - Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237434/

相关文章:

objective-c - 在重写的类方法中调用 super

java - 覆盖方法中的变量名不正确

python - 如何覆盖 Python 中的函数调用?

javascript - 如何删除 twitter-bootstrap-rails 中多余的 css 和 js 链接

ruby-on-rails - 在 MongoDB 上实现自动完成

ruby-on-rails - 一起模拟 rspec 和 mocha

interface - Go:从嵌入式结构覆盖接口(interface)方法

ruby-on-rails - 错误 : Could not find GNU compatible version of 'tar' command while installing RVM

ruby-on-rails - ActiveRecord as_json 返回不同的列名

ruby-on-rails - 在 Ruby on Rails 中覆盖 setter 方法的正确方法是什么?