Archive for December, 2008

The curious case of beauty in Ruby (or Rails vs Merb part 2)

Saturday, December 27th, 2008

I’m sure you’ve all heard the Rails 3 announcement. When I first found out my initial reaction was “fuck me“. But shortly after I was filled with a feeling of dread and general unease. And I didn’t know why ….

Firstly, a bit of history.

I first tried programming on a Commodore Vic 20, and then after that a C64. C64 BASIC was very simple – if you wanted to do anything beyond PRINT statements you needed to POKE values into registers and control the hardware directly. Great for learning how things actually worked. And, to be fair, I was shit at it.

But I do remember reading an article on a system called “Smalltalk” and its “Object Oriented Programming”. Suddenly, programming made sense. It read a bit like English. You sent messages to the thing that knows how to answer your question. It was like talking to people. You ask Dave a football question. You ask George a music question. Cos Dave knows crap all about music and George knows nothing about football.

But, in those days, Smalltalk cost a fortune; there was no way a child like me could get hold of a Smalltalk environment. So instead, I got hold of Turbo Pascal 6 With Objects (thanks Dad). It was not Smalltalk but it read a bit like English and it had objects. I played about with Turbo Pascal, went to university (where I didn’t do computing but did do some C++) and then got a job doing Delphi (Turbo Pascal for the 90s). This object-oriented stuff really worked for me; I put a lot of effort into writing classes that had really simple public interfaces and with code that read like English. And Pascal (the language underlying Delphi) was great for that. Then I discovered Java, which meant I could write Delphi-like code but with having to deal with memory management. I also discovered PHP, Python and Ruby. None of which clicked with me; dynamic typing made me nervous (and PHP and Ruby seemed a bit ugly).

However, I needed an ORM for a Delphi project and I thought I should try to copy an open source project. Whilst searching I discovered Rails and thought “this is the one to copy”. But a day into my “copy ActiveRecord into Delphi” plan I thought “this is just like Smalltalk”. Why make an inferior copy when I can use something that’s not far off the Holy Grail. Writing an application on Rails had the same effect on me as my original discovery of Smalltalk – it read like English, it felt fantastic. So I gave up on Delphi and became a Rails programmer.

What I liked about Rails was its emphasis on happiness. When I wrote Rails code I felt like I was writing beautiful prose. I would go back and refactor it until it read correctly. This was not like pure Ruby, which was often ugly. No; Rails had this idea about beauty in code that really got me excited. It made me happy. It also made decisions for me – put your code here, test it like this, set up your database this way. But Rails had performance problems – so Merb was born. A ground-up rewrite of many of Rails’ ideas but with an emphasis on configurability and performance.

Maybe it’s the Engine Yard connection (I turned Engine Yard down for a job because it didn’t “feel right”) – and now I work for Brightbox, one of their competitors – but for some reason, every time I tried Merb I just couldn’t get into it. It was weird. Structurally and functionally it was the same as Rails – but it was Rails plus performance plus options. And I didn’t like it. I never got past the tutorials. Merb emphasises clear and understandable code and was tested with RSpec (which I love). Rails is hard to understand and uses Test::Unit (which is ugly). But I love Rails and I can’t get into Merb. I just couldn’t figure out why.

Until today.

Mr Hanson did a blog post on his first piece of Rails-Merb integration. And something stood out at me. As he was describing Merb’s provides/display functionality I noticed that I didn’t really “get it”. provides made sense, but how does that relate to display. Mr H addresses that directly:

There were a couple of drawbacks with the provides/display duo, though, that we could deal with at the same time. The first was the lack of symmetry in the method names. The words “provides” and “display” doesn’t reflect their close relationship and if you throw in the fact that they’re actually both related to rendering, it’s gets even more muddy.

And then he describes the Rails 3 version of the same functionality. Instead of provides/display it becomes respond_to/respond_with. In particular display @users becomes respond_with @users.

It’s only a tiny thing. Logically and functionally, they are exactly the same. But DHH’s version has an emphasis on the words that are used. How they couple together (display/provide versus respond_to/respond_with).

And there is the reason that I was uneasy about Rails 3. What if Rails lost this emphasis on the human factors – how the words mesh together – in the search of performance. Merb is written functionally, Rails is written emotionally – Merb is about performance, Rails is about feelings.

But DHH has made me feel much better about Rails 3 – he has shown that he will take Merb constructs and Railsify them, humanise them. Because, although code is executed by computers, it is written, and more importantly, read by people like me.

If you find this useful then please take a look at some of my other writing – or recommend me on Working with Rails. Cheers.

Writing tests for your controllers improves the design of your models

Saturday, December 20th, 2008

I’ve recently been updating some old code – partly written by someone else, partly written by myself. At the time, I thought I had written this code really well; looking back on it now, it looks awful. Fair enough, I’ve learnt a lot – I want to look back on old code and shudder. But also, there is very poor test coverage on this app and the tests that there are are quite unwieldy due to an over-reliance on fixtures.

So I’ve been reworking them all using RSpec, my fork of RSpec-Rails and my Object Factory (which means I can avoid fixtures).

Most of the work involves writing a spec that mimics the current behaviour (by inspecting the code and trying to match all paths through it), then refactoring the code, using the spec to prove that I haven’t broken it.

But some points have some really horrible code (and lots of it) within the controllers. As you probably know, Skinny Controllers is the Rails way – your application logic belongs in your models (as they are your application) – the controller should just find or create the relevant model, ask it to do something and then render the results.

Because of this, I opted to just rewrite the actions in question.

To do this I started by writing a Cucumber feature describing things from the user’s point of view. Actually writing the steps that match the feature was a lot of work; because Cucumber is a full stack test you have to deal with all the dependencies that your individual action has (for example, are you logged in with the correct permissions with all associated objects created and in the right state?).

Then I wrote a controller spec. Controller specs in RSpec should use mock objects; you don’t really want to test the models, you just want to prove that the controller finds or creates the right model, asks it to do something and renders the correct output at the end.

So a typical spec looks something like this (note that this is not RESTful as it was an existing part of the application that I am about to change):


  it "should process an item" do
    @item = mock_model Item, :work_type => :buy_stuff, :quantity => 2

    on_getting :process_item, :id => '1' do
     Item.should_receive(:find).with('1').and_return(@item)
      @stuff = mock_model Stuff
      @item.should_receive(:process).and_return(@stuff)
    end

    assigns[:stuff].should == @stuff
    response.should be_success
    response.should render_template('admin/orders/process_item')
  end

This basically says:

  • We have an item, of type “buy stuff” with a quantity
  • When the process_item action is called, we expect that the controller will try to find the item with the given id
  • Then we should call process on the item and it should give us some stuff
  • The stuff should be stored in an instance variable, called stuff
  • And a page should be successfully rendered using the process_item template

That’s a pretty succinct explanation of what the controller should do – I can’t think of many ways of making that skinnier. It also bears no resemblance to the actual implementation of the action – which currently looks something like this:


def process_work_item
    @item =Item.find(params[:id])
    case @item.product.class.to_s.underscore.to_sym
    when :buy_stuff
      @stuff = Stuff.build_item(@item)
      @stuff.setup_new
      render :action => :process_stuff
    when :update_stuff
      @item.stuff.prepare_for_update
      render :action => :update_stuff
    else
      render :status => 404, :text => "Item product type #{@item.product.class.to_s} unknown."
    end
rescue ActiveRecord::RecordNotFound
  render_not_found
end

Pretty complicated – and as new types of item are added we need to add more and more clauses to that case statement.

First things first – I’ve said that we should call “process” on the item class. So I add a pending spec to the Item specification – this is to remind me that I’ve got some work to implement later on.


  it "should process itself based upon its work type"

Then I rework the controller so that the controller spec passes.


    @item =Item.find(params[:id])
    @stuff = @item.process
    render :template => "admin/orders/process_item"

Pretty simple huh?

What we have done is shifted the logic from the controller into this new “process” method on the Item. We have made it so that the controller knows virtually nothing about the item – all it knows is how to find it and that it has a process method. All the implementation details are now hidden within the Item, out of the way of the outside world.

Through the use of mocking we can ignore actual implementations and concentrate on presenting ourselves as simply, and minimally, as possible to the outside world. This reduces coupling, increases flexibility and makes our code easier to read. Don’t you agree?

Think Visibility

Saturday, December 20th, 2008

The irrepresible Dominic Hodgson is organising his very own conference in March 2009.

It’s all about SEO, marketing and those dirty things us coders try not to get involved with :-) Of course, I will be there.

So why not give Think Visibility a go? You may just learn something.