Archive for November, 2006

pm: Print Methods

Thursday, November 9th, 2006

Ruby has a very convenient method to inspect objects: “p”. It just prints the result of “inspect”. And it’s exactly what irb uses to show the result of each expression.

Anyway, the cool guys at projectionist just posted a little method of theirs called “m”, which provides easy access to an object’s methods.

That made me remember my old (well, not that old) “pm” method for irb, which even if I haven’t talked about here, I’ve made public at dotfiles as part of my irbirc (it’s the last method).

Anyway, looking at their implementation, I decided to polish mine and release it here:

ANSI_RESET        = "33[0m"
ANSI_BOLD         = "33[1m"
ANSI_GRAY         = "33[1;30m"
ANSI_LGRAY        = "33[0;37m"

def pm(obj, *options) # Print methods
  methods = obj.methods - (options.include?(:more) ? [] : Object.methods)
  filter = options.select {|opt| opt.kind_of? Regexp}.first
  methods = methods.select {|name| name =~ filter} if filter

  data = methods.sort.collect do |name|
    method = obj.method(name)
    args = "(" + case method.arity <=> 0
    when 1
      (”a”..(?a + method.arity - 1).chr).to_a.join(”, “)
    when -1
      (”a”..(?a - method.arity - 1).chr).to_a.join(”, “)
    else
      “”
    end + “)”
    klass = $1 if method.inspect =~ /Method: (.*?)#/
    klass = $1 if klass =~ /((.*?))/
    [name, args, klass]
  end
  max_name_length = data.collect {|item| item[0].size}.max
  max_args_length = data.collect {|item| item[1].size}.max
  data.each do |item|
    print ” #{ANSI_BOLD}#{item[0].rjust(max_name_length)}#{ANSI_RESET}”
    print “#{ANSI_GRAY}#{item[1].ljust(max_args_length)}#{ANSI_RESET}”
    print ”   #{ANSI_LGRAY}#{item[2]}#{ANSI_RESET} n”
  end
  data.size
end

Don’t try to understand it unless you can understand it :-)… just copy it to your .irbrc (you do have an irbrc file, don’t you?). And use it like this:

pm "a"

pm "a", :more

pm "a", /regexp/

Rails script/server and terminal windows

Wednesday, November 1st, 2006

Here’s a little hack for those of you that run Rails’ script/server on its own window or tab.

By inserting a couple of lines into the server script, you can have it change the title of the window or tab it’s running on, making it a lot easier to look for it when you have lots of windows open.

Server Tab

All you need is to change “script/server” so it looks like this:

#!/usr/bin/ruby
print 33]2;Rails Server07 # xterm window title
print 33]1;Rails Server07 # screen/iterm tab title

require File.dirname(__FILE__) + /../config/boot
require commands/server

print 33]1; 07 # screen/iterm tab title
print 33]2; 07 # xterm window title

The second set of prints will clear the title after the server terminates. You might want to adjust it to suit your needs.