tail -f findings.out

An improved ruby debugger invocation

I’d been wanting to write a post for some time on improvements I’ve found useful in using Ruby’s debugger. Friend Trevor Rosen beat me to the proverbial punch, however. Give his post a read first, I’ll wait.

Now on top of his suggestions I have one more refinement to add. I’ve defined a snippet in vim for whenever I need to use the debugger. You should be able to define the same in whatever editor you use (and if your editor can’t do snippets, get a real one). When in an .rb file, “debug” + Tab becomes:

1
require 'ruby-debug'; Debugger.settings[:autoeval] = true; debugger; rubys_debugger = "annoying"

In addition to the format Trevor suggested (which calls the necessary module, turns on auto evaluation, and calls the debugger itself) this adds a simple assignment after the debugger is called. I often find this necessary because I want to debug right at the very end of a given suite, a conditional, a method, etc. But if you invoke the debugger as the last statement in such a situation, it won’t actually be called. Here’s an example file:

1
2
3
4
5
6
7
8
9
#!/usr/bin/env ruby

def troubled_func(var1)
  puts "Entering troubled function..."
  secret_num = rand(10) * var1
  require 'ruby-debug'; Debugger.settings[:autoeval] = true; debugger
end

troubled_func(5)

When you run this, you won’t get a debugger console. All the output you get is “Entering troubled function…” and the script exits. If instead you add the assignment I list above after debugger is called, you will get to the debugger console. Sad, but true. (You can select a less offensive assignment if you wish. I settled on it in disgust.)

Aside from this, the Ruby debugger is a useful and beautiful thing. So add the snippet and forget about it.

Tags: ,
September 26, 2009 - 8:17 PM No Comments

Improved irb configuration

As applies to most new tools I start to use, the time in which I’ve started to learn Ruby has included a fair amount of time improving my general working environment, to make it more suited to the use of a welcome new tool. Aside from seeking out informative and reliable sources of documentation, new useful modules, and additions to my editor to make it more Ruby-friendly, I’ve also sought a more efficient configuration for irb. I discussed irb and how to setup some basic improved config in this recent post.

Commenter Vorian helpfully mentioned that the same effect can be achieved through an .irbrc file. This file can then be placed in a VCS, and in addition having the configuration in one spot is preferable. While seeking information on the configuration options available, I came across a number of additional customizations that have proved quite useful. I took this page’s suggestions mostly verbatim in formulating mine. This page was also helpful. Here’s my current .irbrc, highlights to follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Interactive Ruby console configuration
IRB_START_TIME = Time.now

# Print to yaml format with "y"
require 'yaml'
# Pretty printing
require 'pp'
# Ability to load rubygem modules
require 'rubygems'
# Tab completion
require 'irb/completion'
# Save irb sessions to history file
require 'irb/ext/save-history'

# Not stdlib
require 'map_by_method'
require 'what_methods'
# For printing time in session
require 'duration'
# For coloration
require 'wirble'

# Include line numbers and indent levels:
IRB.conf[:PROMPT][:SHORT] = {
  :PROMPT_C=>"%03n:%i* ",
  :RETURN=>"%s\n",
  :PROMPT_I=>"%03n:%i> ",
  :PROMPT_N=>"%03n:%i> ",
  :PROMPT_S=>"%03n:%i%l "
}

IRB.conf[:PROMPT_MODE] = :SHORT
# Adds readline functionality
IRB.conf[:USE_READLINE] = true
# Auto indents suites
IRB.conf[:AUTO_INDENT] = true
# Where history is saved
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"
# How many lines to save
IRB.conf[:SAVE_HISTORY] = 1000

# Turn turn on colorization, off other wirble wierdness
Wirble.init(:skip_prompt => true, :skip_history => true)
Wirble.colorize

# Quick benchmarking facility
# Based on rue's irbrc => http://pastie.org/179534
def quick(repetitions=100, &block)
  require 'benchmark'
  Benchmark.bmbm do |b|
    b.report {repetitions.times &block}
  end
  nil
end

# Return only the methods not present on basic objects
class Object
  def interesting_methods
    (self.methods - Object.new.methods).sort
  end
end

# Prints how long the session has been open upon exit
at_exit { puts Duration.new(Time.now - IRB_START_TIME) }

You’ll need to install the following gems (”sudo gem install FOO”): map_by_method, what_methods, duration, and wirble. Most options should be self-explanatory and there’s plenty of commentary.

With this in place, you’ll get tab completion to assist in remembering method names and automatic indentation to make visualizing your code’s structure simpler. Output will be colorized for quicker understanding. Your activity will be recorded for later review, and when you exit you’ll find out how long you were in the session.

irb

The two methods defined are helpers for benchmarking and viewing the methods on an object that are more interesting:

methods

For more information on irb use, check out this section in Programming Ruby.

Tags: , ,
July 18, 2009 - 9:18 PM Comments (2)

A better Ruby prompt

The Interactive Ruby Shell, or irb, is indispensable for trying out Ruby code rapidly, seeing what works and what’s elegant. But the defaults aren’t quite optimal.

Tab completion

It lacks tab completion by default. Having this available can save you a lot of time, especially as you are learning the language. To turn it on, simply add the option “-r irb/completion” to require that functionality. You can also add it to a running session by entering “require ‘irb/completion’”. After setting this you can press Tab after a dot following an object to see what methods are available for it (not all methods shown in image):

tab-complete

Now you can type the method you want to use from the list. You can also type part of a method name and press Tab to view matches on what you have so far.

Appearance

The default prompt can also be a little too wordy:

default-irb

This shows the program name (always “irb(main)” for the irb command), the line number within said program, and the indentation level. This last value is incremented as you move into loops and other multi-line structures. If you don’t want this meta information, however, just call irb with the “–simple prompt” option:

simple-irb

Aliases

I combine the above customizations into two Bash aliases for simpler access. Just add the following to your ~/.bashrc:

1
2
alias r="irb --simple-prompt -r irb/completion"
alias irb="irb -r irb/completion"

Now you can get to a simpler prompt for quick checks, or the full prompt for more complete documentation, making a tutorial, etc. And both have the lovely tab completion.

[EDIT, 2009-07-17]: As helpfully pointed out by commenter Vorian, the improvements above can also be attained using configuration options placed into ~/.irbrc. After hearing about this, I looked around for example .irbrc files and put together a decent one. Check out this post for more details.

Tags: , , ,
June 21, 2009 - 9:36 AM Comments (3)

Ruby, Rails, and Gems: Getting Started

I recently started learning Ruby (mostly to flesh out my programming knowledge) and since one of the main self-detected shortcomings in my programming knowledge and skillset is web frameworks and web programming, I decided to give Ruby on Rails a shot. This post will describe the first steps needed to begin using Ruby, Ruby on Rails, and their entourage. I’m running Ubuntu 9.04 Jaunty Jackelope, but there are many guides out there to get you up and running. It will also cover some basic tips for using RubyGems and other related topics to get you going faster. Thanks to friend and co-worker Trevor Rosen for ample (cough, truculent, cough) encouragement, information, and assistance in this bauble-strewn journey.

First install Ruby and a few related items:

1
sudo apt-get install ruby rdoc irb

RDoc allows you to generate HTML API presentations from Ruby code. irb is the interactive Ruby prompt, great for trying out quick ideas.

Next you need to install RubyGems. RubyGems is the Ruby packaging system, as easy_install is to Python and apt-get is to Ubuntu. It’s a lovely package handling system. While I use and love setup_tools, it does have its shortcomings. RubyGems actually allows you to uninstall packages! Sounds simple enough, but easy_install users know this is a continual pain. RubyGems also allows much better searching and provides more information about potential packages.

I don’t recommend installing this from the Ubuntu repos. I ran into some odd problems, while the latest from RubyForge worked fine. If you do get it from the repo, be sure to install “rubygems”, not “gem” (Graphics Environment for Multimedia – PureData library)! To install from source, get the latest stable version from here on RubyForge, then:

1
2
3
4
tar xzvf rubygems-VERSION.tgz
cd rubygems-VERSION/
sudo ruby setup.rb
sudo ln -s /usr/bin/gem1.8 /usr/bin/gem

That last step is needed since the setup script doesn’t make its own symlink. This can make for wretched confusion… Here are some basic RubyGems commands and example output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# View available commands
> gem help commands
GEM commands are:
...All the commands and descriptions thereof.
# Search for a gem by name:
> gem query --remote --name-matches flickr
*** REMOTE GEMS ***
flickr (1.0.2)
...Many more...
# Install a gem:
> sudo gem install --remote flickr
Successfully installed flickr-1.0.2
1 gem installed
# Get information on an installed gem:
> sudo gem specification flickr
--- !ruby/object:Gem::Specification
name: flickr
version: !ruby/object:Gem::Version
version: 1.0.2
...Lots more...
# Remove a gem:
> sudo gem uninstall flickr
Successfully uninstalled flickr-1.0.2

Consider adding a few Bash aliases for faster access to the basic commands:

1
2
3
4
5
6
7
8
9
10
# Look for gems with "gquery name":
alias gquery="gem query --remote --name-matches"
# Install new gems with "ginst name":
alias ginst="sudo gem install"
# Get information on gems with "ginfo name":
alias ginfo="sudo gem specification"
# Remove gems with "gdel name":
alias gdel="sudo gem uninstall"
# Update gems:
alias gupdate="sudo gem update"

Next install Rails and its merry band:

1
sudo gem install rails

The Rails Logo was created by Kevin Milden and is distrubuted under the BY-ND Creative Commons Licence.

This will install Rails, its library dependencies, rake, etc. I first installed Rails via apt-get, but ran into a small issue.

Next, to get the general sense of creating a Rails app, I recommend starting off with The Original Ruby on Rails Screencasts by Sam Stephenson and David Hansson on ShowMeDo. These are by no means comprehensive guides, but they illustrate doing some basic things with Rails, and end up with some pretty nice apps in a few minutes. You’ll be hard pressed to follow along yourself, depending on how many hours of Doom you played as a child.

To really start to grasp things, check out the Getting Started guide on the RailsGuides site. This goes through each step from nothing to a working Rails app. As you proceed, you might want additional information on various technical details. Look no further than the Rails Searchable API site. You can browse this online or download it locally. It provides a decent looking (finally for an HTML API: readable) and useable API reference for Rails. The search is amazing, and they’ve done a great job compressing a lot of information into a relatively small amount of space.

Once you begin looking for information on how to accomplish various discrete tasks, check out Railscasts. These assume some Rails knowledge, but are decent simple guides to how to add features like reliable authentication, avoiding SQL injection, generating PDFs, and a lot more (160 so far!).

I hope to post more on Ruby and Ruby on Rails as I learn and play around with them. If you are new to Ruby, check out this page. I came across it after I started going through a few tutorials, and find it amply summarizes most of the features I started to love at first blush.

Tags: , , ,
May 10, 2009 - 3:28 PM Comments (3)

Twitter links powered by Tweet This v1.6.1, a WordPress plugin for Twitter.