Wouldn’t it be nice if when an error happened in your application, you could not only see the stack trace, but click on a line and jump to the offending code? This is not groundbreaking stuff, I know, I had this like 10 years ago in C++ and later Java fat clients, and I’m sure other languages & IDEs had it too – but somehow in moving to writing web apps in Ruby, I lost it.

I want it back damnit!

Turns out it’s pretty easy to get back (at least it is if you use textmate) – check it out.

Custom Error Page

First, to get a custom error page for your project, add something like this to your application.rb :

1
2
3
4
5
def rescue_action_locally(*args)
  render :template  => "application/public_error", :layout => false
end
  
alias rescue_action_in_public render_action_locally

Note, if you’re using exception notifiable, you probably want to change the last line to something like :

1
2
alias render_404 rescue_action_locally
alias render_500 rescue_action_locally

We use markaby, so our public_error template looks something like this; it’s probably a good idea to keep this simple and not use a layout, just in case the error came from the layout :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
html do
  head do
    title action_name
    stylesheet_link_tag 'error'
  end
  body do
    div.error do
      div.message do
        h1 "Whoops"

        p "We detected an error.  Don't worry, though, 
we've been notified and we're on it."
      end
    end
  end
end

Adding a Stack Trace w/ Links to the Error Page

So, it would be helpful to us for our error page to tell us more in our development and staging environments. We do use exception notifiable, so we don’t actually need or want it to say anything else to a real user in production. Adding this to our template, it now looks like this :

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
html do
  head do
    title action_name
    stylesheet_link_tag 'error'
  end
  body do
    div.error do
      div.message do
        h1 "Whoops"
        
        p "We detected an error.  Don't worry, though, 
we've been notified and we're on it."
      end

      if RAILS_ENV != 'production'
        div.stack_trace do
          h2 "Stack Trace"
          div { link_to_code $!.to_s.to_s.gsub("\n", "<br/>") }
          hr
          div { link_to_code $!.backtrace.join("<br/>") }
        end
      end
    end
  end
end

What’s that “link_to_code” method in there?

It’s a method in application_helper that replaces any path with a textmate url to open up that file on your local system and jump to the offending line. Check it out :

1
2
3
4
5
6
def link_to_code(text)
  text.gsub(/([\w\.-]*\/[\w\/\.-]+)\:(\d+)/) do |match|
    file = $1.starts_with?("/") ? $1 : File.join(RAILS_ROOT, $1)
    link_to match, "txmt://open?url=file://#{file}&line=#{$2}"
  end
end

That’s it. Suddenly, stack traces are friendly again!

So, following rSpec’s example, we’re moving from JIRA to Lighthouse. Check us out at http://cruisecontrolrb.lighthouseapp.com/

I have to say I wasn’t thrilled about Jira. It does everything, and it does it slowly, with a UI that is bloated at best. Lighthouse, on the other hand, keeps it REALLY simple. And does not a lot more than what we need. It also just opened itself up for OSS projects (which is cool).

How did we migrate all of our stories from JIRA to Lighthouse? I thought you’d never ask.

Lighthouse exposes a slick RESTful API for managing your data. I exported the JIRA issues into a csv file, wrote a short ruby script, waited about 5 minutes for it to run, and I was done.

Here’s the script:

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env ruby
require 'rubygems'
require 'csv'

JiraIssue = Struct.new(:issue_type, :key, :status, :assign_to, 
                       :summary, :description, :fix_version, 
                       :reporter, :priority, :original_estimate, 
                       :votes)

def load_issues(csv_file)
  header = true
  issues = []
  CSV.open(csv_file, 'r') do |row|
    if header
      header = false
    else
      issues << JiraIssue.new(*row)
    end
  end
  issues
end

issues = load_issues(File.dirname(__FILE__) + "/jiraissues.csv")

# this code is just to examine what our JIRA data looks like
def show(issues, field)
  puts "#{field} = #{issues.map{|i| i.send(field)}.uniq.inspect}"
end

show issues, :issue_type
show issues, :status
show issues, :assign_to
show issues, :fix_version
show issues, :reporter
show issues, :priority
show issues, :original_estimate
show issues, :votes

# these hashes translate between JIRA and Lighthouse
states = {
  "Open" => 'open',
  "Resolved" => 'resolved',
  "Closed" => 'invalid'
}

users = {
  "Unassigned" => nil,
  "Alexey Verkhovsky" => 10545, 
  "Rolf Russell" => 17992, 
  "Jeremy Stell-Smith" => 10638, 
  "Zhang Lin" => nil, 
  "Jeff Xiong" => nil
}

milestones = {
  "1" => 9885,
  "1.1" => 9886, 
  "1.2" => 9887, 
  "1.3" => 9888, 
  "1.4" => 9889, 
  "\302\240 " => nil, 
}

require File.dirname(__FILE__) + "/lib/lighthouse"
include Lighthouse

Lighthouse.account = "cruisecontrolrb"
# enter your own user, password here...
Lighthouse.authenticate "jeremystellsmith@gmail.com", "*******" 

issues.each do |i|
  # enter your own project id here...
  ticket = Ticket.new :project_id => 9150

  ticket.title = i.summary
  ticket.body = i.description
  ticket.state = states[i.status.to_s.strip]
  ticket.assigned_user_id = users[i.assign_to.to_s.strip]
  ticket.milestone_id = milestones[i.fix_version]
  ticket.tags << i.issue_type << i.priority
  
  ticket.save
end

There was another step. I ran the first part of the script a couple times to tell me what the different issue_types, statuses, assigned users, fix versions, etc were that my JIRA data was using. I then found or created the appropriate data in Lighthouse and added some hashes to translate for me.

All in all, I’m pretty thrilled with how easy this was.

Using Markaby w/ Rails 2.0.1

December 13th, 2007

Rails 2.0.1 is out, in general, it’s pretty nice. Markaby doesn’t play too nice w/ it. Markaby requires every named route to have a .to_s on the end of it. Yuck.

After migrating my 3rd project to rails 2.0.1, I got sick of adding .to_s to each named routes, and did some digging.

Apparently, somehow a string coming from a named route is not exactly a string. Sure


  apples_path().class == String

but


  String === apples_path()

is NOT true. I couldn’t quite track down why this was but it eventually leads to a

ActionView::TemplateError (undefined method `string_path' for #) on line #10 of messages/index.mab:

actionpack-2.0.1/lib/action_controller/polymorphic_routes.rb:27:in `send!'
actionpack-2.0.1/lib/action_controller/polymorphic_routes.rb:27:in `polymorphic_url'
actionpack-2.0.1/lib/action_controller/polymorphic_routes.rb:31:in `polymorphic_path'
actionpack-2.0.1/lib/action_view/helpers/url_helper.rb:79:in `url_for'
actionpack-2.0.1/lib/action_view/helpers/url_helper.rb:144:in `link_to'
...

After an hour of trying in vain to find the source of the problem, I found a simple hack that fixes this. Should have thought of this before, but add this code to your application_helper.rb

1
2
3
  def string_path(string)
    string
  end

If anyone else has a better solution, please pass it over!

So I’m a big fan of iWork ‘08, pages is nice enough, doesn’t get in my way, etc. Numbers is pretty awesome. It’s been a while since someone did something revolutionary in the spreadsheet world. Numbers is it.

I do have a couple gripes.

1) if I open a word or excel file, when I save, it should be saved back to that same word or excel file. Not all my friends have macs, let alone iWork, why can’t I save back to the file I opened? And if I have to do the extra export step, why does iWork forget where the file came from? Grr.

2) I am a total excel power user, and numbers is still missing a bunch of features for addins, macros, etc. It doesn’t even have applescript support yet as far as I can tell (I’m sure it will, though, and I am glad they released before they had it) I’ve been getting by on a manual export to csv so I can munge data.

3) and what this blog post is about, is that iWork does not play nice w/ subversion.

iWork stores it’s files in “bundles” which are actually directories even though they look like files from finder. When you have stored one of these bundles in subversion, there will be .svn directories inside of it, containing subversion metadata. The problem comes that every time you save a file in iWork, the entire bundle is replaced w/ the new copy…and ALL .svn directories are destroyed.

This basically renders subversion useless for iWork files. This is no good, there are some pretty painful workarounds on the net, and there are a few scripts that turned up, but I wrote my own.

This script (I call it svn_restore_dirs) will search any subdirectories of the current working directory for files ending in .numbers, .pages, etc. It will then redownload .svn directories for any of these that are missing theirs.

Seems to work, and is simple enough. I wish apple would get their act together.

Enjoy the script

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
#!/usr/bin/env ruby

require 'fileutils'

EXTENSIONS_TO_SEARCH = %w(numbers pages key graffle)
TMP_DIR = "/tmp/missing_svn"

def find_directories_without_svn_dirs
  search_pattern = EXTENSIONS_TO_SEARCH.map {|ext| "-name \"*.#{ext}\""}.join(" -or ")
  dirs = `find . \\( #{search_pattern} \\) -type d`.split("\n")
  dirs.reject {|dir| File.exists?(File.join(dir, ".svn"))}
end  

def get_url_for(file)
  info = `svn info "#{file}"`
  raise "can't parse #{info}" unless info =~ /URL\: (.*)/
  return $1
end

def copy_svn_dirs(from, to)
  to = File.expand_path(to)
  Dir.chdir from do
    Dir["**/.svn"].each do |svn_dir|
      FileUtils.mv svn_dir, File.join(to, svn_dir)
    end
  end
end

find_directories_without_svn_dirs.each do |dir|
  url = get_url_for(File.dirname(dir))

  puts "replacing svn dirs for #{dir} from #{url}/#{File.basename(dir)}"
    
  FileUtils.rm_rf(TMP_DIR) if File.exists?(TMP_DIR)
  `svn co "#{url}/#{File.basename(dir)}" #{TMP_DIR}`

  copy_svn_dirs(TMP_DIR, dir) if $? == 0
end

Pretty Printing Seconds in Ruby

October 16th, 2007

I must have written various versions of this code 20 times so far in my career, but never so quickly and cleanly. I love ruby.

1
2
3
4
5
6
7
8
9
10
11
12
    min, sec = sec / 60, sec % 60
    hour, min = min / 60, min % 60
    day, hour = hour / 24, hour % 24
    week, day = day / 7, day % 7
    
    [
      week > 0 ? "#{week} weeks" : nil,
      day > 0 ? "#{day} days" : nil,
      hour > 0 ? "#{hour} hours" : nil,
      min > 0 ? "#{min} minutes" : nil,
      sec > 0 ? "#{sec} seconds" : nil
    ].compact.join(", ")

The really cool thing is the multiple assignment that ruby lets you do. I haven’t used it for something exactly like this before, but I do use it often and it’s really nice.

I feel like there should be a better way to do the bottom half of this, but this is pretty damn readable, I think. You might have to have a little rubyFU to remember what compact does – which is get rid of the nils.

Anyway, this was about 15 minutes of work (and I did it test first).

It’s very easy to call out to methods in markaby, but it’d be nice if you could actually customize the dsl as well.

For example, on many of our pages we have a bottom row that has buttons that look a certain way. So on every page, we have :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  table(:width => "100%") do
    tr do
      td.left do
        previous_button
        first_button
      end
      td.center do
        print
      end
      td.right do
        next_button
        last_button
      end
    end
  end

The code for the actual buttons changes, and after a few tries to extract the whole thing into a single method, we gave up. Our efforts had made it harder to read, not easier. There was always just a little too much variance, and it didn’t feel right.

What we really wanted to write was :

1
2
3
4
5
6
7
8
9
10
11
12
13
  last_row do
    column do
      previous_button
      first_button
    end
    column do
      print
    end
    column do
      next_button
      last_button
    end
  end

This lets the buttons that change all stay in the view, and gets rid of the skeleton and positional stuff that doesn’t change. Furthermore, it’s DRY and puts all that positional logic in one place instead of scattered across 20 views.

How to do this?

I wrote a test (in RSpec) that looks something like :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
describe ApplicationHelper do
  it "should generate a table from a buttons method" do
    last_row(:columns => 2) do
      column do
        "foo"
      end
      column do
        "bar"
      end
    end.should == '<table width="100%"><tr>' +
                    '<td class="left">foo</td>' + 
                    '<td class="right">bar</td>' +
                  '</tr></table>'
  end
end

After a bunch of fiddling and poking around, I finally made the test (and a couple others) pass with this code in my ApplicationHelper :

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
def last_row(options, &block)
  markaby do
    table(:width => "100%") do
      tr do
        LastRowContext.new(self, options[:columns]).
                                  instance_eval(&block)
      end
    end
  end
end

class LastRowContext
  def initialize(markaby, columns)
    @markaby, @column_count, @column_index = 
                            markaby, columns, 0
  end
  
  def column(&block)
    alignment = case @column_index += 1
    when 1 : :left
    when @column_count : :right
    else :center
    end
    
    @markaby.instance_eval do
      td(:class => alignment, &block)
    end
  end
end

I’m sure this could get cleaned up more; this was the work of less than an hour. In particular, if you did this often, you could extract a common MarkabyContext superclass that had some convenience methods. The point is, this is really easy to do, and we shouldn’t be scared to try “Language level refactorings” like this.

Daemonizing a Ruby Script in Rails

September 20th, 2007

This took way longer than it should have, so I thought I’d jot down what I did so it might take less time next time.

1. Install the daemons gem


sudo gem install daemons

2. Presumably you have a script that looks something like this already

1
2
3
4
#!/usr/bin/env ruby
require File.dirname(__FILE__) + "/. ./config/environment"

SchedulerDaemon.new.run

This is a scheduler script that lives in the scripts directory of a rails project.

3. You’re going to take this code and wrap it in daemon stuff, like so

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env ruby
RAILS_ROOT = File.expand_path(File.dirname(__FILE__) + '/. .')

require 'rubygems'
gem 'daemons'
require 'daemons'

Daemons.run_proc("scheduler", 
                 :log_output => true, 
                 :dir_mode => :normal, 
                 :dir => "#{RAILS_ROOT}/log") do
  require File.join(RAILS_ROOT, "config/environment")
  SchedulerDaemon.new.run
end

The really hard part for me was debugging it. Which meant figuring out how to get logging going. With this code, you can just tail “log/scheduler.output” and see the contents of any puts in the code. Once I started doing that, everything else was easy.

RAILS_ROOT has to be set first, because daemons changes the current working directory. Also, I use the log dir, because it’s shared by capistrano, so I can deploy, then stop / start my scheduler and not worry about losing my first pid file – plus that’s where logs are supposed to go.

4. To make my life just a little easier, I also added some debugging statements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Daemons.run_proc("scheduler", 
                 :log_output => true, 
                 :dir_mode => :normal, 
                 :dir => "#{RAILS_ROOT}/log") do
  begin
    require File.join(RAILS_ROOT, "config/environment")

    puts "starting scheduler at #{Time.now} for #{RAILS_ENV}"
    SchedulerDaemon.new.run

  ensure
    puts "ending scheduler at #{Time.now}"
  end
end

This was actually pretty easy, and next time it will take 5 minutes to create a daemon. Nice gem.

I solved a complex problem in cruise today with some non-trivial mocking. Check this one out :

I needed to test that every x amount of time, we do a clean checkout. It can be every 6 hours, 2 days, whatever. How do you test this?

Well, maybe you could mock the time.


Time.stubs(:now).returns(Time.now + 2.hours)

That almost works, except that the code works by touching a file. And touch doesn’t use Time.now. Now at this point, we could go crazy, and mock FileUtils.touch, of course that means we’ll also have to mock File.exists? and then what are we really testing?

Instead, I used Mocha to temporarily replace FileUtils.touch with my own implementation that acts like the original but uses my own value of time. It looks like this so far.

1
2
3
4
5
6
7
8
  marker = sandbox.root + '/last_clean_checkout_timestamp'

  now = Time.now
  FileUtils.stubs(:touch).with(marker).returns(proc do
    File.open(marker, 'w') {|f| f << ''}
    File.utime(now, now, marker)
  end)
  Time.stubs(:now).returns proc { now }

you’ll notice that both of these stubs are returning procs that reference now a local variable….

That’s ruby magic.

It means that I can now forget about mocks and write the rest of my test like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  @project.do_clean_checkout :every => 1.hour

  assert @project.do_clean_checkout?
  assert !@project.do_clean_checkout?

  now += 59.minutes
  assert !@project.do_clean_checkout?

  now += 2.minutes
  assert @project.do_clean_checkout?
  assert !@project.do_clean_checkout?

  @project.do_clean_checkout :every => 2.days
  now += 1.day + 23.hours
  assert !@project.do_clean_checkout?

  now += 2.hours
  assert @project.do_clean_checkout?

Instead of changing the mocks several times in between each test, I can just change my local variable now. Because of closures, the mocked out methods return the new value.

Ruby is awesome (and Mocha is pretty sweet too)

Creating Change

March 30th, 2007

on a recent e-mail thread, a friend asked for advice when introducing agile. here’s a cleaned up version of my response to him.

Solve THEIR problems, don’t push your own agenda

if you go to people and tell them agile is the key, they won’t listen to you. instead, go to people and listen to their problems. propose and implement solutions to their biggest and worst one or two. check back with them and make sure they are happy (or at least happier) rinse and repeat. if something in the “agile” toolset doesn’t scratch an itch they have, then you shouldn’t be using it. be flexible in everything except your values. be compromising. if they see you give in to what they suggest, they will be more willing to give in to what you suggest.

obviously a retrospective is a great vehicle for this. if you can get the team as a group to admit to problems that they NOT YOU are worried about, then the solutions you come to will also be owned by the team.

Start with individuals, not the “team”

as an outsider, which we are as consultants, it’s very, very hard to convert an entire team to our way of thinking. it’s hard to know what they all think, and the more you push, the more it becomes YOU vs THEM. not good. it’s much better if you can identify the change agents in the team, find the connectors, the mavens, and the salespeople (see The Tipping Point ) and talk to them. it’s much easier to convince one person, one on one that you have some good ideas, and that you might be able to solve some of their problems. do this first, and instead of 1 vs 10 it becomes 2 vs 9 or even 3 vs 7, MUCH better odds. if you can do this with the most influential people, then convincing the rest of the team almost takes care of itself.

this of course works the other way around, too. the most influential people on the team can easily turn the entire team against you, so you have to make sure that you are listening to them. addressing their problems and concerns, and making them feel heard. this is of course good advice for the whole team, but it’s so much easier when it’s one person at a time, you might as well start there.

Ask for help, and dish out the credit

it’s a funny thing, but when you ask someone for help, you usually get it. and believe me, if you’re trying to introduce agile, you’ll need all the help you can get. the easiest help to get is advice that is asked for one on one. ask your boss what the social makeup of the team is. ask those teammates for advice on what the team needs. ask someone to give a part of a presentation to management.

from their perspective, it’s a great thing to be asked for help. it means the person asking respects your opinion about something. it also means that they now owe you something and you’re less likely to hesitate if you need help from them. it means that you take ownership of the thing that you helped create.

if you can manage to make people look good in exchange for your efforts, not only will you spread out the work, but you’ll win yourself friends.

Read the Secrets of Consulting

‘Nuff said.

Object Mother...in rails?

March 6th, 2007

That’s right, the circa 2000 pattern still makes sense today. Use an “object mother” as a test factory to conveniently create objects for your unit tests to bang against. It will often default values, or have different states in which to create objects. For example, you might have a new_user, as well as a new_superuser and new_guest method all of which return users.

Read about the original pattern

But why, you ask, not just use rails’ fixtures? Glad you asked.

  1. it’s more intuitive and maintainable to setup the data you need right next to the test
  2. it’s easier to create just exactly the objects you need when you have test factory methods

But don’t take my word for it. Let’s look at some code.

First off, what does this look like in ruby? I am creating an “ObjectMother” module, which I then just mixin to my tests. A test might then look like :

1
2
3
4
5
6
7
  include ObjectMother

  def test_delete_project
    project = new_project('foo')
    post :delete, :id => project.id
    assert_raise(ActiveRecord::RecordNotFound) { Tag.find(project.id)}
  end

The magic is in “new_project”. It’s an entirely pragmatic construct. If you pass it a string, it will set everything else to acceptable defaults, and use that string as a name. It looks something like this.

1
2
3
4
5
6
7
8
9
module ObjectMother
  def new_project(options)
    options = {:name => options} if options.is_a? String
    options[:url_name] = options[:name].gsub(/\W/, '') if !options.has_key?(:url_name)
    Project.create!(options)
  end

  ...
end

Here in project, it defaults the url_name (which must be unique) from the name you’ve given it. However, you could also create a more custom project by running this :


  new_project(:name => 'garage', :url_name => 'the_garage', :description => 'foo')

This is how it works for projects, but it’s only purpose in life is to make my life easier and reduce the amount of code one has to type or read. So each type of thing it creates works a little bit differently according to our needs


A more complicated example

I was playing with ferret last week, and wrote a test that looked like this :

1
2
3
4
5
6
7
8
9
10
11
  def test_across_types
    project = new_project('rabbit holes')
    post = new_post(:subject => 'a rabbit has a big head')
    user = new_user(:display_name => 'rabbit head')

    @search.string = 'rabbit'
    assert_find [project, post, user]
    
    @search.string = 'rabbit head'
    assert_find [post, user]
  end

My thought process was something along the lines of :

  1. I want to test that my searcher works across types
  2. I need to create a project, post, and user that all have a term in them (in different places)
  3. I want to search for the term, and make sure i get all of them
  4. I want to search for a term that maybe 2 of them have and make sure I only get those 2

Writing the test for this part literally took 30 seconds, I didn’t have to go lookup the fixtures or add a new fixture for my new case. I also didn’t have to remember all the things that it takes to make a valid project or post or user.

Doing a lot of rails work, I’m getting a good feel for testing in ruby and rails. Here are some tricks / snippets I use :

assert_raises takes a string and/or a class

I want to be able to write

one = Project.new('one')

projects << one      
assert_raises('project named "one" already exists') do
  projects << one
end

I’ve done this a few times, but I think cruisecontrol.rb’s implementation is the most robust :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  def assert_raises(arg1 = nil, arg2 = nil)
    expected_error = arg1.is_a?(Exception) ? arg1 : nil
    expected_class = arg1.is_a?(Class) ? arg1 : nil
    expected_message = arg1.is_a?(String) ? arg1 : arg2
    begin 
      yield
      fail "expected error was not raised"
    rescue Test::Unit::AssertionFailedError
      raise
    rescue => e
      raise if e.message == "expected error was not raised"
      assert_equal(expected_error, e) if expected_error
      assert_equal(expected_class, e.class, "Unexpected error type raised") if expected_class
      assert_equal(expected_message, e.message, "Unexpected error message") if expected_message.is_a? String
      assert_matched(expected_message, e.message, "Unexpected error message") if expected_message.is_a? Regexp
    end
  end

assert_equal_sets

In Java, I used to push things into sets and compare them when I didn’t care about order. In ruby, I sometimes use assert_equal_sets. It does a compare of two arrays independent of order. So

1
2
  assert_equal_sets [1, 3, 5], [3, 5, 1]   # passes
  assert_equal_sets [2, 3], [3, 4]    # fails
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Array
  def reorder_like!(other)
    tmp = dup
    clear
    other.each {|x| self << tmp.delete(x) if tmp.index x}
    tmp.each {|x| self << x }
  end
end

class Test::Unit::TestCase
  def assert_equal_sets(expected, actual)
    actual.reorder_like!(expected)
    assert_equal(expected, actual)
  end
end

file_sandbox for testing against the file system

After dragging this code around me for the last 6 or 7 projects I’ve been on, I finally packaged it up as a gem . It lets you write code like :

1
2
3
4
5
in_sandbox do |sandbox|
  sandbox.new :file => 'b/a.txt', :with_contents => 'some stuff'

  assert_equal 'some_stuff', File.read(sandbox.root + '/b/a.txt')
end

Basically it creates a temporary directory for you to muck about in. After the block is ended (or teardown is called on your test) that directory and everything in it is guaranteed to be cleaned up. It also has a bunch of methods to make file based things easier like creating a file, etc.

Install it with “gem install file_sandbox”

Accessing Private Data in Ruby

January 29th, 2007

Of course that’s how you do it…


user.instance_eval("@password")

Every now and then you really do need to access a private variable and don’t particularly want to change the class. Especially in test code. Maybe it’s a smell, but I’d resorted to reopening classes and adding attr_accessor’s.

Moral issues aside, this is definitely a more elegant way of doing it.

Setting Today in a Test

December 20th, 2006

Ruby is awesome…
1
2
3
4
5
6
7
8
  def test_on_weekday
    today_is "May 3, 2006" do
      calendar.add("a call").at(4.pm).on(:saturday)

      assert_equal(Time.local(2006, 5, 6, 16),
                 calendar.appointments.first.start)
    end
  end

...playing with code examples for our book.

Stand ups as Huddles

December 20th, 2006

We’ve been talking about stand ups here at ThoughtWorks.

I’m actually not a big fan of the traditional yesterday – today – issues format. I find that too often it becomes a status meeting – this is what I did yesterday, doing more of the same today, and no issues.

Instead of a status meeting, I like to treat it as a planning meeting. I prefer to think of a stand up like a huddle in American football. The point is to focus on today, and figure out a game plan that makes the most sense. Who needs to pair with whom? Who’s tackling what stories?

I find the signal to noise ratio is much higher in the latter format as is the energy. It’s fine to mention anything from yesterday that is especially pertinent or interesting to the team, but I think the focus should be on today.

Effective Writing

December 8th, 2006

Our publishers have given us a deadline of the end of the year to get 60 pages out for DSLs in Ruby. That’s not a lot of time, but honestly probably a really great thing for us. We needed the push.

Putting everything else on hold for the month, I’ve found myself scrambling to find a way to apply all the discipline that I have when programming to writing. It’s hard, and getting started is always the hardest part.

I’ve gone through many days of “working” yet getting nothing done. This is what I’ve learned, it’s working for me, maybe it will work for you :


Work top down

I remember outlining when I was writing papers in school. I never particularly cared for it. I could pretty much keep the structure of my paper in my head and just write from that. Turns out that’s not actually true for a book. And it’s even less true when you are writing a book with 4 authors in 3 different timezones.

Get a loose outline for the whole book, and then as you write each chapter, outline that in detail. Work on one chapter at a time.

Question Driven Writing

XP has TDD to keep you honest. If it’s not making a test pass, you should delete it or write a test for it.

In a similar way, why not start a chapter by writing the questions it should answer. If you find yourself writing text that doesn’t answer one of those questions, delete it, or add the question.

Work in Sprints

I find I simply CAN NOT concentrate if I’m online and checking mail and talking to my roomates and answering IM’s… As damaging as switching context is when I’m coding, it’s several times more damaging when I’m writing.

The problem is that there’s always more to learn, so it’s way easy to get distracted. Oh, Joe’s online, let’s see if he knows about declarative programming. Let’s google for metaprogramming. Let’s download rBehave.

Even working on examples can be a rabbit hole. And with no pair to pull me back to what we should be doing, I’ve wasted weeks on not important stuff.

The solution?

Figure out what needs to get done next. Do some outlining or research or write some examples, whatever. Once you’re confident that you have some material to write about, start a sprint.

I’m using 2 hour increments, but I could probably do 3 or 4.

  1. Unplug the wifi, evdo or lan cable.
  2. Take a minute to think about what you’re about to do (call it a mini standup) tell someone if, say your girlfriend’s available
  3. Set your timer for 2 hours and write.

The rules are you have to be making forward progress. If you come up against any hurdles, want to ask someone a question, park it. Write it down on a card or a “todo.txt” file.

What do you do when you write?