Ruby:如何从类方法设置实例变量?
我不确定这是这个问题的正确标题,但我不知道该怎么问。我有需要在全球注册的类,以便以后可以调用它们。除了一个非常重要的部分外,我的大部分工作正常。当子类从父类继承时,它会注册一个新实例,但是当调用Ruby:如何从类方法设置实例变量?,ruby,inheritance,subclass,instance-variables,Ruby,Inheritance,Subclass,Instance Variables,我不确定这是这个问题的正确标题,但我不知道该怎么问。我有需要在全球注册的类,以便以后可以调用它们。除了一个非常重要的部分外,我的大部分工作正常。当子类从父类继承时,它会注册一个新实例,但是当调用on_messageclass方法时,我不知道如何设置所需的实例变量 class MyExtension < ExtensionBase on_message '/join (.+)' do |username| # this will be a callback function u
on_message
class方法时,我不知道如何设置所需的实例变量
class MyExtension < ExtensionBase
on_message '/join (.+)' do |username|
# this will be a callback function used later
end
end
class ExtensionBase
def self.inherited(child)
MainAppModule.registered_extensions << child.new
end
def self.on_message(string, &block)
# these need to be set on child instance
@regex = Regexp.new(string)
@on_message_callback = block
end
def exec(message)
args = @regex.match(message).captures
@on_message_callback.call(args)
end
end
# somewhere else in the code, I find the class that I need...
MainAppModule.registered_extensions.each do |child|
puts child.regex.inspect # this is nil and I dont want it to be
if message =~ child.regex
return child.exec(message)
end
end
classmyextension MainAppModule.registered_extensions我终于找到了一个可行的解决方案,现在我添加了整个可执行代码。只需将代码存储在文件callexample.rb
中,然后通过ruby callexample.rb
我对这个问题的解决方案的主要区别在于,现在通过调用on_message
创建具有相关参数的实例,并注册创建的实例。因此,我删除了继承的方法,因为我不再需要它了
我添加了一些put
语句来演示代码的工作顺序
class MainAppModule ## Added class
@@registered_extensions = []
def self.registered_extensions; @@registered_extensions; end
end
class ExtensionBase
attr_reader :regex
def self.on_message(string, &block)
MainAppModule.registered_extensions << self.new(string, block)
end
def initialize(string, block)
@regex = Regexp.new(string)
@on_message_callback = block
end
def exec(message)
args = @regex.match(message).captures
@on_message_callback.call(args)
end
end
class MyExtension < ExtensionBase
on_message '/join (.+)' do |username|
# this will be a callback function used later
puts "Callback of #{self} called."
"returnvalue"
end
end
# somewhere else in the code, I find the class that I need...
MainAppModule.registered_extensions.each do |child|
puts "Value of regex: #{child.regex}" # this is no more nil
message = '/join something'
if message =~ child.regex
puts "On match evalue 'child.exec(message)' to: #{child.exec(message)}"
end
end
class MainAppModule##添加了类
@@注册的_扩展=[]
def自注册扩展名@@注册的扩展;结束
结束
类扩展库
属性读取器:正则表达式
def self.on_消息(字符串和块)
MainAppModule.registered\u扩展