Rendering partials in toto

April 19th 2012

toto is a fantastic lightweight blogging engine. In fact, at the time of writing, this very blog is running on it. By looking at dorothy you can see how it uses a layout and templates to render content. However, by default, it does not provide support for template partials.

However, that’s easily solved with a little monkey patching:

module Toto
  class Site
    class Context
      def to_partial(page)
        to_html page, @config
      end
    end
  end
end

Now you can include partials in your templates like this:

<%= render 'sidebar', :partial %>

Now, I’m not a fan of monkey patching for a number reasons, not least of which is the fact that a good monkey patch is often a missed opportunity to improve an open source project. With that in mind, here is the pull request to have this functionality added to toto itself.

tags: toto, ruby

Stunning landscape photography by Peter Zeglis

April 16th 2012

These images, reminiscent of work by Ansel Adams, were taken in Iceland by Peter Zeglis.

01 02 03 04

More of his Iceland project can be seen here.

Duplicate Active Model validation errors

April 12th 2012

When attempting to test a model using Active Model validations, I came across a rather odd problem.

require 'active_model'

class Person
  include ActiveModel::Validations
  validates_length_of :name, :maximum => 40, :message => 'name too long'
  attr_reader :name
  def initialize(attrs)
    @name = attrs[:name]
  end
end

I was seeing duplicate 'name too long' error messages in the errors hash.

describe Person do
  describe 'validation' do
    it 'should be invalid if name is too long' do
      person = Person.new(:name => 'a' * 41)
      person.should_not be_valid
      person.errors[:name].should == ['name too long']
    end
  end
end

The above spec failed with the following message:

Failures:

  1) Person validation should be invalid if name is too long
     Failure/Error: person.errors[:name].should == ['name too long']
       expected: ["name too long"]
            got: ["name too long", "name too long"] (using ==)
     # ./spec/person_spec.rb:17

Some further digging revealed that the Person was being loaded twice by the require method. require was being called twice with two different paths, which both resolved to the file containing Person. Removing the extra call to require fixed the issue. This seems to be a problem particular to ruby 1.8.7.

The runnable code examples reproducing this issue can be found here.

subscribe subscribe to this blog

Welcome. Here you'll find Adam Scott's blog and photos. Adam is an agile software developer by trade and a photographer by night.

stuff

popular tags