It's a spec, not a test
June 03, 2010  comments

You must have heard the question several times on the Rails mailing list and different IRC channels: "Should I test validates_uniqueness_of"? The standard answer to that one is "No, you definitely should not. It's Rails framework code, and it's already thoroughly tested. If you followed this path, you should also test whether objects are properly persisted in the database."

I think, however, that the question is wrong and thus you can not give a correct answer. It is wrong because validates_uniqueness_of is the implementation, not the requirement. If you approach it from this angle, the question turns into whether you should test the specific implementation or whether you should verify that (business) requirements are met.

That, in turn, comes down to tests vs. specs (short for specifications) and this is again an opportunity for specs to shine. If you write specs instead of tests (or, to put it in a more mind-warping way: if your tests are actually specs), then the above question is a no-brainer: it's part of the specification that no two users can have the same email address, so you must have a spec for it:

describe User do
  it "has a unique email address" do
    Factory(:user, :email => "jeff@topnotch.com")
    lambda { Factory(:user, :email => "jeff@topnotch.com") }.should
     raise_error(ActiveRecord::RecordInvalid)
  end
end

On the other hand, if you stick with calling your tests tests (how orthodox! ;) ) then not only you have to think (which consumes a lot of resources), but you can also come to the wrong conclusion and emit a strong business requirement from your test suite. And then you might not remember to have the implementation for it after modifying the code for whatever reason. And then bad things might happen.

(This thought came to me when coming to work in the subway this morning. I was never quite comfortable with the name "specs" but now it's starting to make a lot of sense to me. You are encouraged to disagree. Dissent is what makes the world progress.)

Remove'em trailing whitespaces!
February 16, 2010  comments

Some of you reading this probably use TextMate. It is an excellent editor with two caveats. The first is that you can only see one file in the editing window (no screen split), the other is that there is no save hook. This latter gave me headaches since I can't stand any trailing whitespace in source code and the easiest solution would have been to run a script to remove those when the file is saved.

Without further ado I'll paste my solution below. Obviously this is not a difficult task to accomplish so the goal is to share not to show off. I use Git for SCM and the following solution parses out the files that have been modified and runs the whitespace eraser script for those. If you use something else (why do you?) you should obviously change the first building block:

parse_modified_files_from_git_status.rb

#!/usr/bin/env ruby -wn
modified_file_pattern = /^#\s+(?:modified|new file):\s+(.*)$/
puts $1  if modified_file_pattern =~ $_

rm_trailing_whitespace.rb

#!/usr/bin/env ruby -wn
$:.unshift(File.dirname(__FILE__))

require "trailing_whitespace_eraser"
TrailingWhiteSpaceEraser.rm_trailing_whitespace!($_)

trailing_whitespace_eraser.rb

class TrailingWhiteSpaceEraser
  FILE_TYPES = ["rb", "feature", "yml", "erb", "haml"]

  def self.rm_trailing_whitespace_from_file!(file)
    trimmed = File.readlines(file).map do |line|
      line.gsub(/[\t ]+$/, "")
    end
    open(file, "w") { |f| f.write(trimmed) }
  end

  def self.rm_trailing_whitespace!(root)
    root = File.expand_path(root)
    files = File.directory?(root) ? Dir.glob("#{root}/**/*.{#{FILE_TYPES.join(',')}}") : [root]
    files.each { |file| rm_trailing_whitespace_from_file!(file.chomp) }
  end
end

And then you run it by typing:

git status | parse_modified_files_from_git_status.rb | rm_trailing_whitespace.rb

If you decide to use this, it is more convenient to download the raw source

Hopefully I did my tiny bit to have less trailing whitespace in OS code.

2010 is the year of the Javascript
January 28, 2010  comments

If you've read the The Pragmatic Progammer - From Journeyman to Master (and if you have not, believe me, you should) you might remember one precious advice: learn a new programming language every year. So when the year draws close to its end (around April, that is) I really start thinking about which language should be the one for me next year.

This reflection is very pleasant; it is such a joy to immerse oneself into a new language, to slowly discover its structure, its subtleties and learn new ways of thinking, of approaching a problem (because that's probably the biggest gain of it, even surpassing adding another language to your arsenal) that its prospect is already rewarding in itself.

My choice in 2009 fell on Clojure. I love functional programming, its elegance, its cleanness, its statelessness and after getting my feet wet with ANSI Common LISP a while ago I felt like Clojure would propel me on my way of becoming an FP guru. Guided by a great book I wrote a couple of, admittedly not too difficult exercises (hey, a sudoku solver is already something, isn't it?) and I would certainly like to continue to do more with it in 2010.

Now, on to 2010.

Thomas Fuchs is certainly right when he predicts that Javascript will play an increasingly significant role in web development. I was definitely wrong when I had thought of JS as an undebuggable, structure- and featureless, incoherent language. Of course, you can write Javascript code that is like this but I now think that -at least in the case of Javascript- this tells more about the craftsman than about the language.

Make no mistakes, I can already do Javascript! I can miraculously make a check box appear if you click on a link, or update a database record without reloading the page when you press a button and a ton more such wizardry, really. However, I always felt like there was a whole lot more to Javascript than putting some dumb-looking functions in a file and then include it from my html (no, I don't think inlining it makes a difference) and I felt uneasy about my javascript functions just standing there on their own without any apparent belonging to a group or some kind of cohesive force or idea that holds them together.

My recent enthusiasm comes from the fact that I had to browse through some of the source code of scriptaculous and I really liked what I saw. The enthusiasm is not totally new but looking at that source code demolished the last shreds of my Javascript skepticism, so to speak. So a year later than Peter Szinek I am hopping on the same train: Javascript, here I come! If you have read a good book that enhanced your Javascript foo, please tell me about it in the comments.

And you? Have you already chosen your language for 2010?

Twuckoo 0.3.5 - With email notification
January 26, 2010  comments

As some of you might know, I am running a few twitter channels that use my brainchild, twuckoo, to periodically send a tweet.

In two of these cases the program takes its next message from a file and takes care not to tweet the same thing twice by keeping track of the messages already sent. This means, however, that the pool of sendable messages are depleted after a while and the script simply does not send any more tweets, the channel becomes dead.

This has happened a couple of times in the past and I only realized it with a few days of delay which is kind of awkward (if you were subscribed to one of these accounts, I apologize). So I decided to have twuckoo send a notification in this case so I can go in and refill its queue. Hence twuckoo version 0.3.5 was born which sends an email to the address set in the configuration file when it failed to send a message.

To install it, add gemcutter to the list of gem sources if you haven't already:

gem source --add http://gemcutter.org

And install twuckoo:

gem install twuckoo

You might be thinking that it would be more straightforward to have the program replenish itself so that no intervention from the part of the developer is needed. And you would be right, this could be a task for the next version. I still think it is a good idea to send a notification so the (wo)man in charge knows it happened.

So go ahead, have a look at the README, set up your own twitter channel and don't fret about when the queue would run dry. You'll be notified.

My tech book list for 2009
January 11, 2010  comments

The title probably tells it all, below is the list of technical books I read in 2009. I am -unfortunately :)- not getting paid for any recommendation that lies herein.

My Job Went to India by Chad Fowler

This one is a real motivation booster. Or it might function like love in the case of separated lovers: if you were motivated in the first place, you'll get a kick out of this book and want to do everything it recommends right from the next day. If you were not it might depress you to have to do so many things to stay afloat. Full of useful advices mostly drawn from the author's personal experience in India. 5/5!

(There is a second, reworked version under the name: The Passionate Programmer, you should probably buy that one.)

User Interface Design for Programmers by Joel Spolsky

I real like Joel Spolsky's essays both for the content and for his witty style. I laughed out loud on several remarks in this book, too. The book reaffirms how important good UI is, makes it accessible for programmers by giving guidelines and provides some examples of good (and especially bad) examples. Its style makes the "dry" technical stuff fun to read.

The Pomodoro Technique by Francesco Cirillo

A time-management and productivity tool, the Pomodoro Technique is the latest craze. The technique can be summarized in a few paragraphs, the details fill about 40 pages which comprise this book. The e-book can be downloaded for free. Although I do not follow all the advices described in the book fully (like administering the tasks you have done at the end of each day) I think the technique is a great way to achieve focus especially if you have problems with it. (The PragProgs have also recently published a book about it)

Programming Clojure by Stuart Halloway

Clojure is a functional programming language that runs in the JVM (hence the "j", I guess). This excellent book contains everything you need to know to start (and continue) programming in Clojure from multimethods to infinite sequences, from ways to deal with concurrency to understanding and writing macros. Clojure rocks and so does this book!

The Principles of Beautiful Web Design by Jason Beaird

I bought this book to be able to do a fancier design than putting black text on white background and using ugly textboxes with Times Roman fonts. It has certainly lived up to this goal and it has some very practical advices and links to resources (I particularly liked the chapter about color). Just as its title says, it explains principles rather than implementation details, which is what I was looking for. That said, I still feel I need another book (and a decent amount of practice, of course) to beam me to the level I had planned to reach before buying it. Any suggestions?

Test-Driven Development By Example by Kent Beck

A true classic, I reckon this book is a must-read for anyone aspiring to adhere to TDD or in fact for anyone already doing it at any level of mastery. In the first two chapters two distinct functionalities are developed (the first one, the Money example, in Java, the second, the xUnit example, in Python) by tiny steps using TDD, at each step pondering on the problem at hand and giving an explanation of the chosen solution. The third and final chapter deals with TDD patterns and is an invaluable addition to the first two chapters. Now that I am writing about it I feel like I should reread this book in 2010 (and then probably once every year). Red, green, refactor!

Pragmatic Thinking and Learning by Andy Hunt

The fact that I have not finished only goes to show its splendidness, I simply don't want it to end yet. (I read this in a Paul Graham essay but I can't find it right now). Its subtitle, "Refactor your wetware", is telling: it shows you how to make yourself more productive by harnessing the innate capabilities of your brain and debugging its intrinsic "bugs". I guess it is also a very refreshing read because it is about our mind and its workings and not some dry technical stuff. The stories and anecdotes linked to some of the sections makes it easy to recall the message. In fact, I liked this book so much I created a "twitter mini-framework" and a twitter channel for the concise version of the advices.

Life is not just about stubbing, view helpers and achromatic color schemes

On a Christmas evening, I sat down on a comfy sofa with Révolutions by J.M.G. Le Clézio in my hand and was totally immersed in it right from page one. I realized I need occasions like this to repeatedly remind myself how much I miss of life if I only ever read technical books. (Sadly, my list of novels I read last year is a lot shorter than the above one but I heartily recommend you A Thousand Splendid Suns by Khaled Hosseini and Poisson d'or by J.M.G. Le Clézio)

Any good books you have read?

I am also making a (so far, only mental) list of books for this year and would like to hear your opinion, too. So have you read any books lately that you would passionately recommend for others?

i15r handles non-english source
January 08, 2010  comments

The other day thinking about how i15r could be improved I realized that there are times when the language of the non-internationalized site is not English (surprise, surprise). Add to this that lots of languages have "special" characters, characters that may not be properly found and replaced by the matchers. So I first learned the basics of how Ruby handles encodings (from James Edward Gray's excellent series) and then adjusted a few matchers to catch those special characters, too. (Note: one can't underestimate the utility of a spec suite that covers most of the code)

The specs pass but I am pretty certain there are some cases where the matchers might not be up to the task. If you come through such a case, please submit a bug report. Since there has been a huge improvement in string encoding in Ruby 1.9 (basically, strings now have an encoding as opposed to in Ruby 1.8), there might be some cases where strings are properly internationalized using Ruby 1.9 but not with 1.8.

So if you think this is a valuable addition or just have not tried i15r yet, go get it:

gem install i15r --source http://gemcutter.org

New year, new blog
January 04, 2010  comments

I guess it all began with this blog post. I saw that there is another way for composing a blog post than typing it into a textarea with a WYSIWYG interface (which is, by the way, never really WYSIWYG). It also seemed a lot cooler, something a "real hacker" would prefer hands down. The decision to switch my blog over to a textarea-free motor has been subconsciously made the time I read that post but the implementation needed a year to be realized. I reckon the final push was to see how easy the migration of the blog's content is.

The tools

I decided to use Jekyll, a static-site generator since it integrates nicely with Github and has all the features I need. Being a static-site generator I needed a client-side solution to handle comments. I chose Disqus because that's the one I knew and liked but there are alternatives.

The process

Content migration

I needed continuity and thus migrating the old posts and comments. Fortunately Jekyll includes migration scripts for several blog motors, among them Wordpress, so that was a piece of cake, everything worked out of the box.

For the comments, I used a modified version of Lackac's script, that he so kindly directed my attention to (thank you, Lackac). Clearly it was more work than migrating the posts but nothing to shy away from. (If you plan to switch from Wordpress to Disqus I believe you'll be able to use the script with a few minor modifications.)

New design

For my Wordpress blog, I used a design template that looked ok but was in PHP and was a PITA to modify or to add some styling to. Since I am looking to improve my capabilities as a designer I thought designing my own blog would be a suitable task to get my hands dirty with. I am not concealing the fact that I borrowed ideas from several blogs I liked but hey, they say it's not a shame to copy good ideas so what's wrong with that?

Layout, site feed, etc. with Jekyll

Have I said I love open source? There is a Jekyll wiki that lists Jekyll sites along with a link to their sources so seeing how to set up my blog with Jekyll was quite straightforward. I guess this was still the most time-consuming part of all but I did not really have to think of anything, the steps are well-defined. (Here is the source of my blog if you'd like to take a glimpse.)

Buying a Github plan to be able to use a non-github domain

If you'd like to host your blog under a custom domain (http://codigoergosum.com instead of http://balinterdi.github.com) you'll need to buy a Github plan. Starting at 7$/month for the Micro plan it's not an insurmountable obstacle, in fact it costs less than the Wordpress hosting I am moving away from.

Changing the name

Back in the spring of 2008, returning from the European Ruby conference (and having finished The Pragmatic Programmer on the train) my mind was buzzing with new ideas and I could not wait to set myself on a craftsman's journey.

I felt I needed a blog immediately. The hard part of course was coming up with a name. Since I felt it was more important to get something going than to idle on finding the perfect one (I guess we can call this agile, can't we? :)), I launched http://bucionrails.com. During the almost two years that have passed since that day I have grown somewhat uncomfortable with that name so I decided to change it. I hope you like the new one :). (I set up a feed redirection with Feedburner to notify you of the feed URL change after 15 days but you could directly subscribe to the new feed now)

The end result

It felt appropriate to start the new year with a new blog and -to my surprise- the switch was a lot easier than I had thought. I hope you, the faithful readers of my blog, welcome the change and ameliorate it with your precious comments.

Now I am blogging like a hacker, too!