The Office is Painted

Posted by collin
on Thursday, October 23

Welcome to the Family, Devon!

Posted by collin
on Saturday, September 06

Congrats to Chris and Michelle!

A companion to Enumerable#inject : Enumerable#build

Posted by collin
on Tuesday, August 19

This was a patch idea I had for Rails. Enumerable#inject is great, but there is a little extra bit of code cruft that I see popping up everywhere with regards to using #inject to create a new array or hash. Since the return value of the block passed into #inject becomes the next value of the accumulator, you often see this:

result = (1..10).inject([]) do |array, element|
  array << element if element % 2 == 0
  array
end

puts result.inspect # => [2, 4, 6, 8, 10]

I’d like to see another method added to Enumerable, something like:

module Enumerable

  def build(accumulator)
    each do |item|
      if result = yield(accumulator, item)
        accumulator = result
      end
    end
    accumulator
  end

end

The #build method would essentially reassign the accumulator only if the return value of #yield was non-false. This would shorten the above example into:

result = (1..10).build([]) do |array, element|
  array << element if element % 2 == 0
end

puts result.inspect # => [2, 4, 6, 8, 10]

So yes, one line of savings, but I feel the meaning here is much more clear than the first case using #inject.

Configure OS X speech voice in growl-glue 1.0.3

Posted by collin
on Tuesday, July 29

Little small update for my small, but loyal growl-glue user base. 1.0.3 released today, giving you the ability to use a different OS X voice for each status.

GrowlGlue::Autotest.initialize do |config|
  config.notification :use_network_notifications => true

  config.sound :success => "Glass.aiff" 
  config.sound :pending => "Glass.aiff" 

  config.say   :failure => "PANIC PANIC PANIC" 
  config.voice :failure => "Hysterical" 
  config.sound :failure => "Basso.aiff" 
end

And of course, to update:

% sudo gem install growl-glue

Implied types in Ruby's rescue clause

Posted by collin
on Tuesday, July 29

There are two different ways in which you’ll see people using rescue in Ruby:

begin
  # do something terrible
rescue
  # handle error in $!
end

And the more explicit way:

begin
  # do something terrible
rescue StandardError => e
  # handle error using e
end

These two are actually equivalent, as the former, shorter version implies that you are catching any error that is or is a subclass of StandardError. The problem is that while StandardError does encompass a large number of different exception types, it still lives under the broader umbrella of Exception:

% cheat exceptions
exceptions:
  Exception
   NoMemoryError
   ScriptError
     LoadError
     NotImplementedError
     SyntaxError
   SignalException
     Interrupt
   StandardError
     ArgumentError
     IOError
       EOFError
     IndexError
     LocalJumpError
     NameError
       NoMethodError
     RangeError
       FloatDomainError
     RegexpError
     RuntimeError
     SecurityError
     SystemCallError
     SystemStackError
     ThreadError
     TypeError
     ZeroDivisionError
   SystemExit
   fatal

The more aggressive way to rescue from error conditions is, then, to:

begin
  # the most terrible code
rescue Exception => e
  # whew
end

Growl-glue update now supports the RSpec "pending" status

Posted by collin
on Sunday, July 27

Growl-glue 1.0.2 was released today. The update adds support for a “pending” status. Without any extra configuration, the gem will use a yellow graphic to match the text in the terminal and will also output a unique title for the growl notification.

The “pending” status is configured similarly to the “failure” and “success” statuses:

GrowlGlue::Autotest.initialize do |config|

    config.notification :use_network_notifications => true
    config.title :success => "Love", :failure => "Hate", :pending => "Keep Going!" 
    config.say :failure => "Something is horribly wrong!" 
    config.say :pending => "I know you can do it!" 

end

To update, simply:

% sudo gem install growl-glue

If you’re wondering what growl-glue is, read the introductory post or the README.

Some specs not being run by rspec-rails? Fix it here.

Posted by collin
on Thursday, July 24

Rspec and the Rspec-Rails plugin are awesome. Made even more awesome by using Autotest. Which is made even more awesome by using growl-glue :)

We’ve noticed on a couple of our projects that Autotest will not run all of our specs that would normally be run by ”% rake spec”. Looking into it further, I saw that the rspec-rails plugin sets up a number of Autotest “mappings”, which are ways of telling the Autotest loop of not only the files that should be tested, but also which specs to run when a source file is modified.

The default mappings can be found in:

RAILS_ROOT/vendor/plugins/rspec-rails/lib/autotest

Autotest#add_mapping takes a regular expression that, if it matches a source file path, can either then return a path or a list of paths that point to the specs that correspond to the source file. If you wanted to return a glob of files, you can use Autotest#files_matching, which takes a regular expression that will return a set of specs that match.

In my case, there are some files in “app/filters” that I want to link up to some specs in “spec/filters”. So, in my .autotest file inside of the project root, I include the following:

Autotest.add_hook :initialize do |autotest|

  autotest.add_mapping(%r%^app/filters/(.*)\.rb$%) { |_, m|
    autotest.files_matching %r%^spec/filters/.*_spec.rb$%
  }

end 

Here I’m pretty aggressive – I simply run all of the filter specs in spec/filters when any file in app/filters is modified. You can get pretty specific though – make sure to check out the default autotest configuration inside of the rspec-rails plugin to get an idea for what’s possible.

If you’re unsure about which specs are not getting run, try running autotest as:

% autotest -v

Autotest will say “Dunno!” for each file for which it doesn’t have a mapping.

Did my team win today?

Posted by collin
on Tuesday, July 22

Did my team win today? is a little rails app that I wrote that will show you if your MLB team won today or not. Well, actually, it’ll just show you the last known score for your team.

Hope you like it.

Terrible Lizards

Posted by collin
on Sunday, July 20

Incredible to think that these once roamed the earth.

Restart Passenger Phusion using a TextMate bundle

Posted by collin
on Sunday, July 13

So I’ve recently started running my development instances using Passenger. It’s been a really nice transition, even with the extra steps of setting up a hostfile and adding an entry into an Apache config file. I know about the OS X preference pane, but I prefer to do the extra steps.

One extra step I don’t like doing is having to touch the [project_home]/tmp/restart.txt file in order to restart the application. Since I do most of my work in TextMate, I decided to write a little bundle so that I wouldn’t have to load up Terminal every time I wanted to restart my application.

You can simply hit the hotkey to restart the app. It’s project relative, so it should work for whatever rails project you happen to have loaded in TextMate.

GrowlGlue : tying together Autotest and Growl

Posted by collin
on Wednesday, July 09

A while ago I blogged about modifying one’s ~/.autotest file and adding all sort of regular expression pattern matching to parse autotest output and then display notifications with images through Growl. Because it’s unreasonable to assume that anyone would actually want to do all of that, I made my first gem: growl-glue.

% sudo gem install growl-glue

And then inside of your ~/.autotest file, something simple like:

require 'rubygems'
require 'growl_glue'

GrowlGlue::Autotest.initialize do |config|
  config.notification :use_network_notifications => true
  config.title :success => "Everything is Great" 
  config.title :failure => "Hate" 
  config.say :failure => "ON NO!!!" 
end

And that’s it! It even comes embedded with sample success and failure images that you can override with your own if you wish (but don’t have to). Make sure to look over the README to get started.

Plugin Migrator: migrations for your Rails plugins

Posted by collin
on Monday, May 26

Overview

My current work involves writing a handful of Rails plugins. These plugins provide additional functionality that includes ActiveRecord models that need to be persisted to the database. I originally created a migration class for one of the plugins that re-used much of the ActiveRecord logic (in fact, just overrides schema management). This worked fine, but as we started creating new plugins that needed the same functionality, we decided to pull the migration logic into a separate Rails plugin.

And hence, the PluginMigrator was born!

In order to use the PluginMigrator, your plugin must simply extend the PluginMigrator::Migrator class:

module MyPlugin
  class Migrator < PluginMigrator::Migrator

    set_schema_table_override "my_plugin_schema_info" 
    set_migration_directory(File.dirname(__FILE__) + "/../../db/migrate") 

  end
end

The set_schema_table_override method tells the plugin where the version info for your plugin should be stored. For rails apps, this schema information lives in a table named “schema_info”. You’ll need to specify a different table name for your plugin, so that your plugin migrations can be managed separately from the Rails app. Don’t worry if it doesn’t exist yet – the migration system will automatically create it.

The set_migration_directory method tells the plugin where to find the migrations. The migrations for your plugin should probably be stored in the same way as the main rails app. In your plugin root, it’s easy to just have a db/migrate structure:

To actually migrate, simply create a Rake task in your tasks directory inside of your plugin or in the main Rakefile for your plugin, depending on from where you want to run the migrate task:

namespace :myplugin do
  desc "Run the migrations for my plugin" 
  task :migrate => :environment do
    MyPlugin::Migrator.migrate(ENV['VERSION'],false)
  end
end

And then:

% rake myplugin:migrate

Typical VERSION behavior is also supported:

% rake myplugin:migrate VERSION=1

Installation

The PluginMigrator project is hosted at GitHub.

From the Terminal:

~/testapp $ cd vendor/plugins
~/testapp/vendor/plugins $ git clone git://github.com/oculardisaster/plugin_migrator.git

If you don’t have Git on your system, you can simply go to the main project page and click the download button.

Known Issues and Planned Features

  • Would like to be able to optionally exclude having the main rails app include plugin tables when writing out the schema.rb file during a Rails app migration.
  • Would like to have the plugin migrator automatically create rake tasks to migrate the plugin

A six hundred+ series

Posted by collin
on Tuesday, May 20

After much research into getting rid of lane oil and finally restoring my ball coverstock back to its near original condition I ruled the lanes today. My first 600+ series. This should help my street cred at league night tomorrow.

:D

Configuring Autotest and Growl in OS X 10.5.x

Posted by collin
on Sunday, May 11

UPDATE – Use GrowlGlue Instead

Autotest Just got a lot simpler.. For an easier time of configuring Autotest and Growl please read Configuring Autotest and Growl in OS X 10.5.x instead.



First off, if you are not running autotest then you need to start. It’s awesome and a pretty integral part of my TDD workflow. A popular combination these days is to run a combination of autotest along Growl. There are already quite a few guides out there on how to set up a development environment with autotest and Growl—why am I writing this one? It is because many of the guides out there do not work exactly right under OS X 10.5.2, making it frustrating to set up these tools. After trying a number of them, and taking what worked right and what didn’t, here is what works for me.

Setting up Autotest

Autotest is part of the ZenTest suite, which should be installed as a gem:

sudo gem install ZenTest

After you install the ZenTest gem, you should then have autotest at /usr/bin/autotest.

Setting up Growl

You can download Growl from the Growl website of course. You will want to install the Growl application normally, but then after that is complete, you will also want to install the growlnotify extra that comes with Growl.

Once you’ve installed Growl and while the DMG is still open, open up a Terminal.app window and execute the following:

cd /Volumes/Growl\ 1.1.2/Extras/growlnotify/
./install.sh 

Now you should be able to test this out by typing the following into the Terminal.ap window:

echo "Hello World" | growlnotify

If you receive a “growlnotify: command not found”, then you need to add /usr/local/bin into your PATH environment variable.

If this fails silently, that is because of an incompatibility between Growl and OS X 10.5.x that will cause dropped messages about 50% of the time. So even if you got the Growl notification, you should install the following fix for Growl.

Fixing Growl

Simply put, on OS X 10.5.x, growlnotify works about 50% of the time for me. To address this, first open up your Growl preferences (under System Preferences), click the network tab, and then make sure that the “Listen for incoming notifications” checkbox is checked. Like this:

After you set that, click back to the General tab, and then Stop Growl, and Start Growl again.

Now, the bug in Growl that I mentioned does not affect incoming network Growl notifications. So we’re going to make a wrapper for growlnotify that will forward received growl notifications to the network port that Growl listens on. Create ~/safegrowlnotify with the contents:

#!/bin/bash

# growlnotify leopard bug workaround
list_args()
{
    for p in "$@" 
    do
        if [ "${p:0:1}" == "-" ];then
            echo -n "$p " 
        else
            echo -n "\"$p\" " 
        fi
    done
}
argstr=$(list_args "${@:$?}")
echo "-H localhost $argstr" | xargs /usr/local/bin/growlnotify

And of course you will want to chmod 755 that file. To test that you have it configured, run thusly:

safegrowlnotify 'Hello World!'

You should have growl notifications coming up now:

Configuring Autotest for Growl

Now that we have everything installed, it’s time to configure Autotest. When Autotest loads up and starts the test loop, it will configure itself from ./.autotest and also ~/.autotest. It is in the latter that we’ll make our Growl modifications. This way the behavior will be shared amongst all projects that use Autotest.

Insert the the following into ~/.autotest (create if it does not already exist):

.autotest

module Autotest::Growl
  GROWLNOTIFY = "/Users/collin/safegrowlnotify" 

  def self.notify title, msg, img, pri=1, sticky="" 
    commands = ["#{GROWLNOTIFY}  --image #{img} -p #{pri} -m #{msg.inspect} #{title} #{sticky}"]
    commands.each { |c| system(c) }
  end

  Autotest.add_hook :ran_command do |at|
    results = [at.results].flatten.join("\n")
    # rpsec
    output = results.slice(/(\d+)\s+examples?,\s*(\d+)\s+failures?(,\s*(\d+)\s+pending)?/)
    if output
      if $~[2].to_i > 0
        notify "Test Results", "#{output}", "~/Library/autotest/rails_fail.png", 2
      else
        notify "Test Results", "#{output}", "~/Library/autotest/rails_ok.png" 
      end
    end
    # test::unit
    output = results.slice(/(\d+)\s+tests?,\s*(\d+)\s+assertions?,\s*(\d+)\s+failures?,\s*(\d+)\s+errors?/)
    if output
      if (($~[3].to_i > 0) or ($~[4].to_i > 0))
        notify "Test Results", "#{output}", "~/Library/autotest/rails_fail.png", 2
      else
        notify "Test Results", "#{output}", "~/Library/autotest/rails_ok.png" 
      end
    end
  end

end

(thanks to samsm for the Test::Unit modifications)

It is very important to change the value of GROWLNOTIFY to whereever you installed it previously. Also, you will want to put the following into ~/Library/autotest (create if it does not already exist). You can use whatever images you’d like, but I used these that some other kind soul before me shared in a similar blog post:

At this point, you should be all set up and ready to go. Simply running autotest should run the tests and then display the Growl messages along with an icon to boot that signifies success or failure:

Happy Autotesting!

Braves vs Padres - 5 wins in a row

Posted by collin
on Thursday, May 08

Thanks to Brett for the nice tickets to the Braves game yesterday. The seats were on the lower level, quite a bit closer than the nosebleeds I usually purchase. If we win today’s game at 1pm, we will have swept the Padres. Go Braves!