在 Ruby 中,从父类和父类的父模块继承的正确方法是什么?



代码

require "fluent/plugin/input"
module Fluent::Plugin
class ParentInput < Fluent::Plugin::Input
Fluent::Plugin.register_input("parent", self)
# Imagine parent_param as an instance variable that ia accessed as @parent_param, which is "Hello"
config_param :parent_param, :string, :default => "Hello"
# 1. Flunetd runs this first
def initialize()
super
log.info "Inside Parent initialize()"
end
# 2. Flunetd runs this after initialize
def configure(conf)
log.info "Inside Parent configure()"
log.info "@parent_param=", @parent_param
Child.new().main()
end
# 3. Flunetd runs this after configure
def start()
super
log.info "Inside Parent start"
hello_world = hello_world()
log.info "hello_world", hello_world # Hello World
end

def hello_world()
log.info "Inside Parent hello_world()"
return @parent_var + " World"
end
end # Parent class
class Child < ParentInput
def initialize()
super
log.info "Inside Child initialize()"
@hello_world = hello_world()
end
def main()
log.info "Inside Child main()"
log.info @hello_world
end
end # Child class
end # Fluent::Plugin module

代码说明

  • 代码的目标是在转到start()之前在configure()中进行设置。

  • 在整个代码中,hello_world()Parent访问,并且一次由Childconfigure()访问

  • Parent类运行主逻辑。它的定义方式是根据文档。-Child类是我为分离功能而添加的。事实上,它做的事情更多。为了演示起见,我把它简化了。

  • 这里使用initialize()super,因为没有它log将无法工作。没有它,它将是nil

  • 当flunetd在下面运行时,可以看到输出,它突出显示了执行顺序:

Inside Parent initialize()
Inside Parent configure()
@parent_param=Hello
Inside Child initialize()
Inside Parent hello_world()
`hello_world': undefined method `+' for nil:NilClass (NoMethodError)
...
  • 正如您从上面看到的,@parent_var在子类中不可用,但log似乎可用,因为它可以打印"Inside Child initialize()"

问题

  • 继承的正确方式是什么:
    • 父的变量/参数(例如:parent_param)
    • 父母的方法(例如:hello_world())
    • 父级的父级或模块(例如:Fluentd中的log)

parent_params替换parent_var应该很好

parent_var未在的任何位置设置/定义

最新更新