代码
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
访问,并且一次由Child
在configure()
访问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
未在的任何位置设置/定义