Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Conor Hunt

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Ruby IRB helper method to pretty-print object methods

A simple method to print out the methods for an object at run time in a nicely formatted and colorized way. Really useful when using irb

Place in your .irbrc for easy usage, example here:
http://dotfiles.org/~sd/.irbrc

usage:
pm object
pm object, :more - shows all methods including base Object methods
pm object, :more, /to/ - shows all methods filtered by regexp

Coded by sebastian delmont

   1  
   2      ANSI_BOLD       = "\033[1m"
   3      ANSI_RESET      = "\033[0m"
   4      ANSI_LGRAY    = "\033[0;37m"
   5      ANSI_GRAY     = "\033[1;30m"
   6  
   7      def pm(obj, *options) # Print methods
   8        methods = obj.methods
   9        methods -= Object.methods unless options.include? :more
  10        filter = options.select {|opt| opt.kind_of? Regexp}.first
  11        methods = methods.select {|name| name =~ filter} if filter
  12  
  13        data = methods.sort.collect do |name|
  14          method = obj.method(name)
  15          if method.arity == 0
  16            args = "()"
  17          elsif method.arity > 0
  18            n = method.arity
  19            args = "(#{(1..n).collect {|i| "arg#{i}"}.join(", ")})"
  20          elsif method.arity < 0
  21            n = -method.arity
  22            args = "(#{(1..n).collect {|i| "arg#{i}"}.join(", ")}, ...)"
  23          end
  24          klass = $1 if method.inspect =~ /Method: (.*?)#/
  25          [name, args, klass]
  26        end
  27        max_name = data.collect {|item| item[0].size}.max
  28        max_args = data.collect {|item| item[1].size}.max
  29        data.each do |item| 
  30          print " #{ANSI_BOLD}#{item[0].rjust(max_name)}#{ANSI_RESET}"
  31          print "#{ANSI_GRAY}#{item[1].ljust(max_args)}#{ANSI_RESET}"
  32          print "   #{ANSI_LGRAY}#{item[2]}#{ANSI_RESET}\n"
  33        end
  34        data.size
  35      end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS