Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
auto-registering child classes with instance variables
# This is all mostly working except for the "on_message" class method.
# It needs to set the regex and block as a variable that can be accessed later from an instance of the 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
# in the main app code, I loop through the registered extensions and test the regex...
MainAppModule.registered_extensions.each do |extension|
puts extension.regex.inspect # this is nil and I dont want it to be
if message =~ extension.regex
return extension.exec(message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment