Refactoring at ORUG 2

Posted by caike on January 19, 2010

Here is the slides for the Refactoring talk I did last Thursday at the Orlando Ruby User Group meeting. In case you want to hear me speaking along with the slides, I’ve put it up on vcasmo also.

Autotesting PHP applications (and others) 3

Posted by caike on January 12, 2010

So you’ve probably heard of ZenTest/Autotest, right?

In case you haven’t, it is a Ruby gem that (among other things) automatically runs your tests whenever it notices that a file in you project has changed. It’s a great productivity boost, because it saves you from having to run your tests each time you make a change to your program. The perfect tool if you are doing TDD.

So I wanted to get this autotest functionality going for projects in other languages - like PHP, for example - but apparently ZenTest/Autotest only works within Ruby projects.

Talking to the EnvyLabs’ guys I was told about Watchr, a Ruby gem that monitors files matched by a regular expression and triggers a user defined command whenever a file changes. That’s enough to get you started in an autotest-like tool for PHP - or just about any other language.

I’ve setup an example PHP project of Watchr playing an autotest role in a PHP project:


View on Vimeo.

The source code from this example can be seen at http://github.com/caike/watchr_running_php

AppleScript for my Rails terminal tabs

Posted by caike on December 10, 2009

While working on a Rails project I always have at least 4 different Terminal tabs that I use for

  1. spork server
  2. autospec
  3. ./script/server
  4. command line stuff (generators and general shell commands)

Setting up the tabs all the time is kind of a boring and repetitive task. This truly deserved some automation and it was the perfect excuse for writing my first AppleScript.

After some googling around I came up with this bash/AppleScript to do these tasks for me (and also open up TextMate):

#!/bin/bash

if [ $# -ne 1 ]; then
    PATHDIR=`pwd`
else
    PATHDIR=$1
fi

/usr/bin/osascript <<EOF
on new_terminal_tab()
	tell application "System Events" to tell process "Terminal" \
        to keystroke "t" using command down
end new_terminal_tab

set actions to {"spork rspec", "autospec", "./script/server"}

tell application "Terminal"
	do script with command "cd $PATHDIR && mate . && clear" \
	in selected tab of the front window
	repeat with action in actions
		my new_terminal_tab()
		do script with command "cd $PATHDIR && " & action \
		in selected tab of the front window
		if action contains "spork" then
			delay 7
		end if
	end repeat
end tell
EOF

If only I had used the right search words I would have found Nick Rutherfor had been through the same situation.

Using Authlogic for general email validation 1

Posted by caike on November 05, 2009

In case you are using Authlogic for authentication in your Rails apps, then you are probably using its email format validation in the user registration step. You get this validation for free just by specifying your model to acts_as_authentic:

class User < ActiveRecord::Base

  acts_as_authentic

end

That’s it for the user model and its registration field validations (login, email and password).

But what if you have some other model in your application with an email field that you also want to validate ? You could just get your favorite email format regexp and use it with the validates_format_of method:

class Band < ActiveRecord::Base

  validates_presence_of :manager, :description
  validates_format_of :email, :with => /SomeRegexpYouGotFromGoogle/

end

But that would be decentralizing the email validation concern - totally anti-DRY and error-prone.

A better solution would be to use the email regexp that’s in Authlogic, which is the same that’s already validating your user model email field.

class Band < ActiveRecord::Base

  validates_presence_of :manager, :description
  validates_format_of :email, :with => Authlogic::Regex.email

end

That’s it. Hope it helps someone keep their code clean.

Writing expressive code 7

Posted by caike on October 07, 2009

Software developers read a lot more code than they actually write. An application source code is nothing but a story written using a specific language. It has state and describes behaviour.

Code written once, will be read millions of times. For the most part, it will be read by a compiler who doesn’t really look for anything but correct syntax. Compilers are not into reading stories. They are too busy for that. Just like assembly-line workers, they follow a plan and do exactly what they were told. As soon as they pass things over to the runtime, they are done. On the other hand, we developers are not like that, are we ? No, we are not!

We are software craftsmen. We like to read stories and even get paid to write some every once in a while.

man_reading_book

http://www.flickr.com/photos/dhammza/91435718/

Think about it the next time you hack that magic one-liner in an application. Do you think you will be able to read that code-golf champion piece of code the next time you look at it ? What if it is not you, but someone else reading it ?

“Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live (…) Alternatively, always code and comment in such a way that if someone a few notches junior picks up the code, they will take pleasure in reading and learning from it.” - Ward Cunningham, CodeForTheMaintainer

An example I like to use for expressive code is method parameters in Ruby. Let’s say you want to stay fit and write a method to calculate a body fat percentage. You write the following:

def body_fat_percentage(name, age, height, weight, metric_system)
end

Apparently it looks nice. Let’s see how it could be invoked:

# fred's height in meters and weight in kilograms
body_fat_percentage("fred", 30, 1.82, 90, 1)

# barney's height in feet and weight in pounds
body_fat_percentage("barney", 32, 5, 300, 2)

In order to write those two calls you would probably have to check the right order for the parameters in the method’s signature. Even worse, every time you read that line you would have to check back its signature just to make sure that the last argument determines the metric system or that the third argument is actually the height and not the weight.

That sounds like a pretty boring story to read!

Let’s make this piece of code more expressive:

# fred's height in meters and weight in kilograms
body_fat_percentage("fred", :age => 30, :height => 1.82,
  :weight => 90, :metric_system => MetricSystem::METERS_KG)

# barney's height in feet and weight in pounds
body_fat_percentage("barney", :age => 32, :height => 5,
:weight => 300, :metric_system => MetricSystem::FEET_LB)

All we need to do to the method signature is to replace the standalone arguments for a hash.

def body_fat_percentage(name, params={})
end

From the method body, the values can be accessed using the keys, like params[:age], params[:height], etc.

In a real life situation, this expressiveness would be achieved from writing our expectations as unit tests. We would first write our failing tests as how we wanted our code to look and act like. From that, we would head towards making the tests pass. When all is green, the tests would turn out to be the reference for how to call the method (running and never-obsolete documentation) so there’s no need to go back to the implementation of the method itself to learn how to to use it.

Writing expressive code often means writing more code, but it also means writing better code. It’s not about making things work, it’s about making things right.