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

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 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

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

    def pm(obj, *options) # Print methods
      methods = obj.methods
      methods -= Object.methods unless options.include? :more
      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)
        if method.arity == 0
          args = "()"
        elsif method.arity > 0
          n = method.arity
          args = "(#{(1..n).collect {|i| "arg#{i}"}.join(", ")})"
        elsif method.arity < 0
          n = -method.arity
          args = "(#{(1..n).collect {|i| "arg#{i}"}.join(", ")}, ...)"
        end
        klass = $1 if method.inspect =~ /Method: (.*?)#/
        [name, args, klass]
      end
      max_name = data.collect {|item| item[0].size}.max
      max_args = data.collect {|item| item[1].size}.max
      data.each do |item| 
        print " #{ANSI_BOLD}#{item[0].rjust(max_name)}#{ANSI_RESET}"
        print "#{ANSI_GRAY}#{item[1].ljust(max_args)}#{ANSI_RESET}"
        print "   #{ANSI_LGRAY}#{item[2]}#{ANSI_RESET}\n"
      end
      data.size
    end

.irbrc - tab completion, cross-session history, history file

My own .irbrc file constructed from this and this.

Put this file in your home directory ("C:\Documents and Settings\USERNAME" on Windows)

If on Windows, create an environment variable called HOME and point it to "C:\Documents and Settings\USERNAME".

require 'irb/completion'
ARGV.concat [ "--readline", "--prompt-mode", "simple" ]

module Readline
  module History
    LOG = "#{ENV['HOME']}/.irb-history"

    def self.write_log(line)
      File.open(LOG, 'ab') {|f| f << "#{line}\n"}
    end

    def self.start_session_log
      write_log("\n# session start: #{Time.now}\n\n")
      at_exit { write_log("\n# session stop: #{Time.now}\n") }
    end
  end

  alias :old_readline :readline
  def readline(*args)
    ln = old_readline(*args)
    begin
      History.write_log(ln)
    rescue
    end
    ln
  end
end

Readline::History.start_session_log

require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"

IRB.conf[:PROMPT_MODE] = :SIMPLE

Run script/console Remotely with Capistrano

From http://errtheblog.com/post/21.
Allows you to execute script/console remotely through Capistrano. Not for use on multi-machine :roles.

desc "remotely console" 
task :console, :roles => :app do
  input = ''
  run "cd #{current_path} && ./script/console #{ENV['RAILS_ENV']}" do |channel, stream, data|
    next if data.chomp == input.chomp || data.chomp == ''
    print data
    channel.send_data(input = $stdin.gets) if data =~ /^(>|\?)>/
  end
end

Irb itches eliminated

I use the following code to print out, edit and re-eval
irb history. A more detailed explanation at:
http://www.chwhat.com/articles/2005/10/08/

require 'tempfile'
HISTFILE = "~/.irb.hist"
MAXHISTSIZE = 300

#borrowed from http://rubygarden.org/ruby?Irb/TipsAndTricks
begin
	if defined? Readline::HISTORY
		histfile = File::expand_path( HISTFILE )
		if File::exists?( histfile )
			lines = IO::readlines( histfile ).collect {|line| line.chomp}
			puts "Read %d saved history commands from %s." %
				[ lines.nitems, histfile ] if $DEBUG || $VERBOSE
			Readline::HISTORY.push( *lines )
		else
			puts "History file '%s' was empty or non-existant." %
				histfile if $DEBUG || $VERBOSE
		end

		Kernel::at_exit {
			lines = Readline::HISTORY.to_a.reverse.uniq.reverse
			lines = lines[ -MAXHISTSIZE, MAXHISTSIZE ] if lines.nitems > MAXHISTSIZE
			$stderr.puts "Saving %d history lines to %s." %
				[ lines.length, histfile ] if $VERBOSE || $DEBUG
			File::open( histfile, File::WRONLY|File::CREAT|File::TRUNC ) {|ofh|
				lines.each {|line| ofh.puts line }
			}
		}
	end
end

## My stuff
class Array
	def multislice(range,splitter=',',offset=nil)
		result = []
		for r in range.split(splitter)
		if r =~ /-/
			min,max = r.split('-')
			slice_min = min.to_i - 1
			slice_min += offset if offset
			result.push(*self.slice(slice_min, max.to_i - min.to_i + 1))
		else
			index = r.to_i - 1
			index += offset if offset
			result.push(self[index])
		end
		end
		return result
	end
end

$original_history_size = Readline::HISTORY.size
def history_list(first_num,second_num=Readline::HISTORY.size - 1)
	Readline::HISTORY.to_a[(first_num + $original_history_size - 1) .. (second_num + $original_history_size - 1) ]
end
def history_slice(nums)
	Readline::HISTORY.to_a.multislice(nums,',',$original_history_size)
end
def history_list_or_slice(*args)
	if args[0].class == String
		history_slice(*args)
	else
		history_list(*args)
	end
end
def print_history(*args)
	puts history_list_or_slice(*args).join("\n")
end
def eval_history(*args)
	eval %[ #{history_list_or_slice(*args).join("\n")} ]
end
def edit_history(*args)
	history_string = history_list_or_slice(*args).join("\n")
	edit(history_string)
end
def edit(string=nil,editor=ENV['EDITOR'])
	editor ||= raise "editor must be given or defined by EDITOR environment variable"
	tempfile = Tempfile.new('edit')
	File.open(tempfile.path,'w') {|f| f.write(string) } if string
	system("#{editor} #{tempfile.path}")
	File.open(tempfile.path) {|f| f.read } 
end
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS