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)

Rails on Ubuntu

[EDIT, 2009-12-20]: For some time I steered away from installing Rails via APT on Ubuntu systems. I ran into a number of annoyances early on trying to get various bits of Ruby, Rails, libraries, and others installed and working together properly. And along the way I just never tested the following on a fresh Ubuntu system:

1
sudo apt-get install rails sqlite3

That’s it. On a freshly baked Ubuntu 9.10 Desktop or Server, this will install (as of today):

  • ruby: 1.8.7
  • rails: 2.2.3
  • irb: 0.9.5
  • rake: 0.8.4
  • rdoc: 1.0.1
  • sqlite: 3.6.16
  • rubygems: 1.3.5

And a host of dependencies of course. Perhaps I had simply FUBAR’ed my system by the time I tried this in the past, but it is working swimmingly now. Most of the other tutorials I’ve come across for Rails on Ubuntu take the more manual approach as well, but for now this looks like the way to go. For comparison, when I went through the more stepwise setup process using the script mentioned in the original content of this post below all the same versions were installed except for Rails itself, which was 2.3.5. So a slightly newer Rails version via gem than the Ubuntu repo, otherwise identical.

What follows is the original, more manual approach to getting everything installed. It might be useful to try if you run into problems with the repo package.


As I tried to get Ruby on Rails up and running on multiple (Jaunty Jackelope) Ubuntu 9.04 boxes, I came across a few… gotchas. While the steps described in this post will get Ruby, Rails and friends in place and working, there are a few places that have other potentially perilous options resulting in much gnashing of teeth.

What follows are the commands needed to get Rails working on a fresh Ubuntu 9.04 (server) box. To save some copying and pasting you can use this script which sets everything up and provides logging.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
sudo apt-get install ruby ruby-dev libopenssl-ruby rdoc irb build-essential
cd /tmp
# Check here to see if this is the latest:
# http://rubyforge.org/frs/?group_id=126
wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz
tar xzvf rubygems-1.3.5.tgz
cd rubygems-1.3.5/
sudo ruby setup.rb
# Without this 'gem' will either not work or will be something else:
sudo ln -s /usr/bin/gem1.8 /usr/bin/gem
# Test:
gem --version
# Should be: 1.3.5
sudo gem install rails
# Test:
rails --version
# Should be: Rails 2.3.2 (or whatever is latest)
# To get sqlite setup (default Rails DB backend):
sudo apt-get install sqlite3
sudo apt-get libsqlite3-dev
sudo gem install sqlite3-ruby

Warnings:

  • Don’t install gem with apt-get. This is not RubyGems. And don’t even install rubygems via apt-get. Install it from RubyForge.
  • Don’t forget to make the symlink from gem1.8. This can cause no end of pain if you didn’t listen to the last warning.
  • After RubyGems is in place, install Rails and other related items you need with it. Don’t use apt-get for these.

For more information on setup, covering DB and web server options on Ubuntu, check out the Community Guide.

[EDIT, 2009-10-04]: I just tried starting up Rails installed through the process above on a fresh Ubuntu 9.04 desktop. Turned out I also had to install libopenssl-ruby via apt-get. This is apparently due to some splitting of packages in the Ubuntu repo.

Tags: , ,
May 17, 2009 - 7:35 PM Comment (1)

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.