超越对宝石的关注-Rails [英] Overriding a concern of a gem - Rails
问题描述
我正在尝试修改一个gem(准确地说是Devise令牌身份验证)以适合我的需求.为此,我想覆盖关注的SetUserByToken中的某些功能.
I am trying to modify a gem (Devise token auth to be precise) to suit my needs. For that I want to override certain functions inside the concern SetUserByToken.
问题是我该如何覆盖?
我不想更改gem文件.有简单/标准的方法吗?
I don't want to change the gem files. Is there an easy/standard way of doing that?
推荐答案
Bear in mind here that a "concern" in Rails is just a module with a few programmer conveniences from ActiveSupport::Concern.
当您在类中包含模块时,该类本身中定义的方法将优先于所包含的模块.
When you include a module in a class the methods defined in the class itself will have priority over the included module.
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
中重新定义所需的方法,甚至可以组成自己的模块而无需猴子修补库:
So you can quite simply redefine the needed methods in ApplicationController
or even compose a module of your own of your own without monkey patching the library:
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"
请参见猴子修补:好,坏和丑陋 a>很好的解释了为什么将自定义代码覆盖在框架或库的顶部而不是在运行时修改库组件通常会更好.
See Monkey patching: the good, the bad and the ugly for a good explanation why it often is better to overlay your custom code on top of a framework or library rather than modifying a library component at runtime.
这篇关于超越对宝石的关注-Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!