Created
November 28, 2011 15:50
-
-
Save andrewhavens/1400852 to your computer and use it in GitHub Desktop.
auto-registering child classes with instance variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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