覆盖 gem 的关注点 - Rails

Pra*_*are 4 overriding ruby-on-rails

我正在尝试修改 gem(准确地说是设计令牌身份验证)以满足我的需求。为此,我想覆盖 SetUserByToken 内部的某些函数。

问题是我该如何覆盖它?

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

max*_*max 5

请记住,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"
Run Code Online (Sandbox Code Playgroud)

因此,您可以非常简单地重新定义所需的方法,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"
Run Code Online (Sandbox Code Playgroud)

请参阅猴子修补:好的、坏的和丑陋的,以很好地解释为什么将自定义代码覆盖在框架或库之上而不是在运行时修改库组件通常更好。