我正在尝试修改一个 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/