我需要創建類的路徑副本,其中對一個模塊方法的呼叫被替換為另一個模塊方法呼叫:
module Foo
def self.check
"foo"
end
end
module Bar
def self.check
"bar"
end
end
class Bark
def call
puts Foo.check
end
end
Bark.new.call => "foo"
Meouw = Bark.dup
...
???
Meouw.new.call => "bar"
任何想法我將如何實作?
uj5u.com熱心網友回復:
不是問題的答案,但我認為你正在嘗試解決 XY 問題,這不是解決問題的方法。
您需要做的是注入依賴項而不是對其進行硬編碼。
module Foo
def self.check
"foo"
end
end
module Bar
def self.check
"bar"
end
end
class Bark
def initialize(checker)
@checker = checker
end
def call
puts @checker.check
end
end
然后只需Bark使用您需要的模塊實體化該類即可獲得具有所需行為的物件:
Bark.new(Foo).call #=> "foo"
Bark.new(Bar).call #=> "bar"
uj5u.com熱心網友回復:
奇怪的問題需要奇怪的解決方案。您可以定義Meouw::Foo并使其參考Bar:
Meouw = Bark.dup
Meouw::Foo = Bar
這樣,Foo內部Meouw將決議為Meouw::Foo(實際上是::Bar)而不是全域::Foo:
Meouw.new.call
# prints "bar"
uj5u.com熱心網友回復:
為什么不能保持簡單并繼承Bark和覆寫該call方法?
class Meow < Bark
def call
puts Bar.check
end
end
Meouw.new.call
# prints "bar"
如果你想要更多元的東西,你也可以Class.new使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537617.html
標籤:红宝石
上一篇:有沒有辦法向用戶回傳nil訊息但不中斷ruby??中的應用程式?
下一篇:將一個類的值賦值給另一個類
