Created
March 31, 2012 06:15
-
-
Save swarley/2259906 to your computer and use it in GitHub Desktop.
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
Pry::Commands.create_command "find-method" do | |
description "find-method: Find a method recursively USAGE: find-method [OPTION] [REGEX] [BASECLASS]" | |
def options(opti) | |
#method_options(opti) | |
opti.on :n, :name, "Search for a method by name" | |
opti.on :c, :content, "Search for a method based on content in Regex form" | |
end | |
def process | |
#puts opts | |
#output.puts method_object.source | |
return if args.size < 1 | |
pattern = eval "/#{args[0]}/" | |
args[1]||="Class" | |
klass = ::Kernel.eval "::#{args[1]}" | |
if opts.name? | |
puts name_search(pattern, klass) | |
elsif opts.content? | |
puts content_search(pattern, klass) | |
else | |
puts name_search(pattern, klass) | |
end | |
end | |
private | |
def puts(item) | |
output.puts item | |
end | |
def content_search(pattern, klass, current=[]) | |
return unless klass.is_a? Class | |
return if current.include? klass | |
current << klass | |
meths = [] | |
(klass.instance_methods - [:__id__]).each do |method_name| | |
meth = Pry::Method.new(klass.instance_method(method_name)) | |
if meth.source =~ pattern | |
meths << "#{klass}##{method_name}" | |
end | |
end | |
klass.constants.each do |klazz| | |
meths += ((res = content_search(pattern, klass.const_get(klazz), current)) ? res : []) | |
end | |
return meths.flatten | |
end | |
def name_search(regex, klass, current=[]) | |
return unless klass.is_a? Class | |
return if current.include? klass | |
current << klass | |
meths = [] | |
klass.methods.each {|x| meths << "#{klass}##{x}" if x.to_s =~ regex } | |
klass.constants.each do |x| | |
meths += ((res = name_search(regex, klass.const_get(x), current)) ? res : []) | |
end | |
return meths.flatten | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment