[英]Ruby class accessing protected method of child class?
我有 Node Js 的背景,我是 Ruby 的新手,如果這個問題是菜鳥,請原諒。 我有3個這樣的班級。
class Babylon::Metric::Counter < Babylon::Metric
protected
def record
# some code here
end
end
class Babylon::Metric::Gauge < Babylon::Metric
protected
def record
# some code here
end
end
這些的父 class 是
class Babylon::Metric
class ArgumentError < ArgumentError; end
def initialize name, category, amount
@name = name
@category = category
@amount = amount
end
def self.call name:, category:, amount:
new(name, category, amount).()
end
# What is it doing here exactly is it calling Counter or Gauge record method from here,
# based on valid method returns true or false?
def call
valid? ? record : notify
rescue => e
begin
raise Babylon::Error, e.inspect
rescue Babylon::Error => e
Babylon::Event.(event: "babylon.error", error: e)
end
end
def valid?
# do validation
end
def notify
# do some stuff
end
end
我認為 call 方法能夠依次調用 Counter class 和 Gauge class 記錄方法如果有效方法返回 true,但我不知道它如何調用,因為這些是受保護的成員?。
如果您初始化父 class 並對其調用call
或record
方法,您將如預期的那樣得到NoMethodError
。 訣竅在於,父級的所有方法在子級中也可用。
這意味着如果您啟動子 class 並在其上調用record
,則子 class 上的記錄方法將完全按預期調用。
而且,如果您在子 class 上調用call
方法,它將使用父的實現,但在子 class 的上下文中,這意味着在其中調用的記錄方法將可用並且不會引發錯誤。
在 Ruby 中, protected
的方法只能通過以下任一方式調用:
say_hello
而不是self.say_hello
) 在父類 class 中,可以看到record
是使用隱式接收者調用的,這意味着該方法可以是 public、protected或private。
例如:
class Foo
def say_hello
whisper_hello # implicit receiver
end
end
class Bar < Foo
private # protected would work as well in this example
def whisper_hello
puts "(hello)"
end
end
在此示例中, Foo.new.say_hello
將失敗,因為父級whisper_hello
中未定義 whisper_hello(換句話說,您可以說Foo
是一個抽象類); 但是Bar.new.say_hello
會工作得很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.