Skip to content

Instantly share code, notes, and snippets.

@t9md
Created October 29, 2010 09:48
Show Gist options
  • Save t9md/653240 to your computer and use it in GitHub Desktop.
Save t9md/653240 to your computer and use it in GitHub Desktop.
register particular method used as command
#!/usr/bin/env ruby
module Kernel
private
def this_method
caller[0][/`([^']*)'/, 1]
end
def calling_method
caller[1][/`([^']*)'/, 1]
end
end
class Command
@@command = []
def self.command_list; @@command end
def register
meth = calling_method
@@command << meth unless @@command.include? meth
end
def registerd?(methname)
@@command.include? methname
end
def meth1; register; "meth1" end
def meth2; register; "meth2" end
end
Command.new.meth1 # => "meth1"
Command.new.meth2 # => "meth2"
Command.command_list # => ["meth1", "meth2"]
class Command2
@@command = []
class << self
def method_added(name)
@@command << name if name.to_s =~ /^cmd_/
end
def command_list; @@command end
end
def meth1; "meth1" end
def meth2; "meth2" end
def cmd_meth1; "cmd_meth1" end
alias_method :cmd_meth2, :meth2
end
Command2.new.meth1 # => "meth1"
Command2.new.meth2 # => "meth2"
Command2.command_list # => [:cmd_meth1, :cmd_meth2]
class Command3
@@command = []
class << self
def command_methods(*meth)
@@command.concat meth
end
def command_list; @@command end
end
def meth1; "meth1" end
def meth2; "meth2" end
def meth3; "meth3" end
command_methods :meth1, :meth2
end
Command3.new.meth1 # => "meth1"
Command3.new.meth2 # => "meth2"
Command3.command_list # => [:meth1, :meth2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment