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!

TextMate Macro - Title Comment Bundle

Posted by collin
on Sunday, April 20

I like to segment my code with comments. I don’t go nuts with it, but it helps me to have a visual delineation of what certain blocks of code do. Usually it will look something like this:

class Boat < ActiveRecord::Base

  # validations ------------------------------------

  validates_presence_of :name
  validates_presence_of :pony
  validates_presence_of :me

  # callbacks --------------------------------------

  def before_save
    #...
  end

  # business ---------------------------------------

end

One problem I run into frequently is trying to keep a consistent right hand side margin with those comments. As the source code grows in length, it becomes increasingly hard to make sure that the right hand side lines up. Even if you’re not OCD, it becomes a bit ugly to have jagged right hand side edges for these comments. So I thought, this is the perfect time to create my first TextMate bundle.

I’ll spare you the details of my failures trying to figure out how to do this. The final macro ended up being Ruby code and made use of the environment variables that TextMate provides to these scripts. It also uses the TextMate::UI class to query the user for the text of the comment title. If text is already selected before the bundle command is invoked, that will be the default for the title.

#!/usr/bin/env ruby

require "#{ENV["TM_SUPPORT_PATH"]}/lib/exit_codes" 
require "#{ENV["TM_SUPPORT_PATH"]}/lib/ui" 

MAX_LENGTH = 80

if text = TextMate::UI.request_string(:title => "Title", 
    :prompt => "Comment Title:", 
    :default => ENV["TM_SELECTED_TEXT"]) 

  result  = "# " 
  result += text
  result += " " 
  result += "-" * (MAX_LENGTH - result.length - ENV['TM_LINE_INDEX'].to_i)
  print result

end

The use of the TM_LINE_INDEX environment variable gives us the column position of the caret on the current line. Using this allows us to ensure that the right hand side always lines up, no matter what indentation one starts on when creating the comment.

I bind the command to ctrl-opt-cmd-c.

If you use this, you probably will want to use the following settings for your macro in the bundle editor:

You can also download the bundle directly if you’d like.

Three strikes and you're out

Posted by collin
on Friday, April 18

But what about eight strikes and a couple of spares to boot?

It was a pretty amazing game.

Rainy Braves

Posted by collin
on Sunday, April 06

Kelly and I had been looking forward to April 4 for a long time. It was to be our first game of the season, and one of four games for which we bought tickets in advance. We were so excited about it that we got to the stadium, checked the time, and found that we had gotten there two hours ahead of game time. Doh!

We had heard about the possibility of rain. I asked Kelly if she wanted to not go to the game because of the rain, and of course she said Hell No. I agreed, it is not in good Braves form to avoid a game because of the possibility of rain.

Soon enough, it started to pour. We knew the game was about to be cancelled when they started playing videos on the huge display. At 7:30 they cancelled it and we went home. Luckily, they are going to make it up on the May 20, and we will be there. Rain or shine.

The Video:

Get the Flash Player to see this player.

The Pictures:

A simple way to create a budget

Posted by collin
on Monday, March 24

Kelly and I were talking this weekend about budgets, and why they were so hard to make. Primarily the problem is that budgets attempt to impose a limit on certain types of spending, and at the same time, people generally don’t have a very clear picture of where their money is going.

As a fun experiment, we talked about creating a small web application to help people figure out where their money goes. The key factor to drive it would be simplicity and ease of use. Using Rails it came together pretty quickly over the weekend and I’ve already started using it.

The key features:

  • Completely web based
  • In place editing for all fields
  • Track your expenses by month
  • Tag your expenses by category
  • Generate reports at any time for the current month
  • Free to use

To get started, head over to Glued To My Money and register for an account.

It’s still pretty basic, but it should work fairly well. Here’s what I would like to do in the near future:

  • Add export to CSV / Excel feature
  • Add SSL to the web server
  • Integrate AmCharts to visualize spending trends

If you sign up and enjoy it (or not), please let me know . I would love feedback.

Screenshots:

I'm in Boston, visiting my brother Brandon

Posted by collin
on Saturday, March 01

Boston is pretty cool. I’m visiting my brother Brandon up here for an extra long weekend.

It’s also pretty cold, but nothing that was shocking.

I’m going to try and remember to take pictures, which I’ll update here.