2016-05-15 100 views
1

我試圖修改一個寶石(設計令牌認證是準確的)以滿足我的需求。爲此,我想覆蓋關注SetUserByToken中的某些函數。覆蓋寶石的問題 - Rails

問題是我該如何覆蓋它?

我不想更改gem文件。有沒有一種簡單/標準的方式來做到這一點?

回答

2

請記住,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爲什麼通常最好將自定義代碼覆蓋在框架或庫上,而不是在運行時修改庫組件。