Ubuntu, Emacs, and Fonts

Ubuntu is a wonderful development environment in many ways, but let’s not beat around the bush: fonts in Linux have always been a disaster. It’s not as bad is it used to be; these days Ubuntu ships with some nice-looking fonts by default and apps mostly use them out of the box. Things get hinky fast, though, if you step off the beaten path. Like, say, if you want to install your own user fonts.

As it turns out, it’s trivially easy to install your own TrueType fonts in Ubuntu; it’s just not at all obvious how. Here’s the secret: simply copy the .ttf file into a directory called “.fonts” in your home directory. You can create the directory if it doesn’t already exist. Next time you start a program the font should be available.

Naturally Emacs has to throw a wrench in the works. Emacs font-handling on Linux can charitably be described as “eccentric” and more bluntly as “schizophrenic”. There are about a half-dozen different ways to specify fonts. The most obvious place is a menu item titled “Set Font/Fontset” under the “Options” menu. As far as I can tell this item is placed in the UI strictly as a diversion; it pops up a bafflingly organized menu of fonts which bears no relation to any other list of fonts on the system, and which are all hideously ugly.

If you are persistent you will eventually discover the “set-default-font” function, which is what you really want. You will type “M-x set-default-font” and then hit TAB to see a list of completions and see a list of a hojillion X11 font spec strings. After frustratedly scrolling around for a while you’ll punch up xfontsel and discover that the the font you are looking for is listed under the “unknown” foundry, or something equally unpredictable. Sensing victory close at hand, you’ll type in the whole font spec (you do know the ISO designation for your native character set, right?) and hit RET.

And then Emacs will spit out an error about it being an “undefined font”.

The completion list, as it turns out, is just another clever ruse. Emacs actually has its own syntax for specifying fonts. I don’t claim to understand this syntax. What I do know is that entries of the form [font name]-[font size in points] seem to work nicely.

So, to summarize, if you want to try out a new TrueType font (for instance, Anonymous) in Emacs, here are the steps:

  1. Put the .ttf file in ~/.fonts, creating the directory if needed.
  2. Type M-x set-default-font RET "Anonymous-10" (without the quotes)
  3. Enjoy your new font.

UPDATE: Emacs informs me that set-default-font is actually deprecated and I should be using set-frame-font instead, Also, if you want to persist this configuration the best way to do it appears to be by adding (font . "Anonymous-10") to default-frame-alist. The Emacs documentation recommends using your ~/.Xresources file for this instead, but in my experience getting X Resources to “take” is something of a crap shoot.

UPDATE 2: If you like the Inconsolata font, do not install the ttf-inconsolata package on Ubuntu 8.10 (or lower). It is broken, and it will override your .fonts version of Inconsolata with it’s nasty brokenness.

UPDATE 3: As of Ubuntu 12.10, I can now report that the newer “fonts-inconsolata” package seems to work fine.

Go Fetch

I’m a fan of the #fetch method in Ruby. I’ve noticed that other Rubyists don’t use it as much as I do, so I thought I’d write a little bit about why I like it so much.

First of all, in case you’ve forgotten, #fetch is a method implemented on both Array and Hash, as well as some other Hash-like classes (like the built-in ENV global). It’s a near-synonym for the subscript operator (#[]). #fetch differs from the square brackets in how it handles missing elements:

  h = {:foo => 1, :bar=> 2}
  h[:buz] # => nil
  h.fetch(:buz) # => IndexError: key not found
  h.fetch(:buz){|k| k.to_s * 3} # => "buzbuzbuz"

The simplest use of #fetch is as a “bouncer” to ensure that the given key exists in a hash (or array). This can eliminate confusing NoMethodErrors later in the code:

  color = options[:color]
  rgb  = RGB_VALUES[color]
  red = rgb >> 32 # => undefined method `>>' for nil:NilClass (NoMethodError)

In the preceding code you have to trace back a few steps to determine where that nil is coming from. You could surround your code with nil-checks and AndAnd-style conditional calls – or you could just use #fetch:

  color = options.fetch(:color) # => IndexError: key not found
  # ...

Here we’ve caught the missing value at the point where it was first referenced.

You can use the optional block argument to #fetch to either return an alternate value, or to take some arbitrary action when a value is missing. This latter use is handy for raising more informative errors:

  color = options.fetch(:color) { raise "You must supply a :color option!" }
  # ...

Another common use case is default values. These are often handled with the || operator:

  verbose = options['verbose'] || false

But this has the problem that the case where the element is missing, and the case where the element is set to nil or false, are handled interchangeably. This is often what you want; but if you make it your default it will eventually bite you in a case where false is a legitimate value, distinct from nil. I find that #fetch is both more precise and better expresses your intention to provide a default:

  verbose = options.fetch('verbose'){ false }

In my code I try to remember to use #fetch unless I am reasonably sure that the Array or Hash dereference can’t fail, or I know that a nil value is acceptable by the code that will use the resulting value.

Writing Facades on Legacy Code

h2. The Setup

Let’s say we have a system in production which manages college financial aid departments. Over the years it has accumulated a fairly complex object model for handling the many kinds of forms a financial aid department has to generate and process. It’s not the most elegant and well-factored model in the world, but it gets the job done.

Here are a few of the classes involved in the forms component of the system:

  class Form < ActiveRecord::Base
    has_many :form_revisions
    # ...
  end

  class FormRevision < ActiveRecord::Base
    has_many :form_sections
    has_many :form_signoffs
    # ...
  end

  class FormSection < ActiveRecord::Base
    has_many :form_questions
    # ...
  end

  class FormQuestion < ActiveRecord::Base
    # ...
  end

  class FormSignoff < ActiveRecord::Base
    # ...
  end

h2. The Problem

One particular subsystem deals with student applications for financial aid. All of the application forms have a common essential format: a section listing acceptance criteria that must be met in order to qualify; a section listing exclusion criteria which might disqualify the student, and a field for the financial aid counselor to sign off that the student filled out the form correctly.

Currently whenever an administrator clicks the “new application form” button, the controller code which creates the new form does it something like this:

  form = Form.create!(:name => form_name)
  first_version = FormRevision.create!(:form => form, :version => 1)
  acceptance_section = FormSection.create!(:name => "Acceptance Criteria")
  rejection_section = FormSection.create!(:name => "Rejection Criteria")
  first_version.form_sections < < acceptance_section
  first_version.form_sections << rejection_section
  first_version.form_signoffs.create!(:name => 'Counselor')

The process for adding a new acceptance or rejection criterion is similarly tedious:

  form = Form.find_by_name(name)
  form_version = form.current_version
  section = form_version.sections.find_by_name('Acceptance Criteria')
  section.form_questions.create!(:text => question_text)

The tests for this logic (which is all contained in controllers) have to duplicate all of this setup in order to exercise the controllers with realistic data. Lately the devs have taken to using Factory Girl to make the setup easier, but it’s still a duplication, and it seems like there’s always some little detail of how the application code assembles a form that differs from how the test code does it. The other day one of the devs tried to debug one of these differences by manually assembling forms in the console, but he quickly got frustrated by all the steps necessary to get the form “just right”.

h2. Facade Methods

Clearly, there is an opportunity for simplification here. One option is to add some facade methods to the Form class which encapsulate the complexity of building application forms:

  class Form
    def self.create_application_form!
      # ...
    end

    def add_criterion(question_text, kind=:acceptance)
      # ...
    end
  end

However, in our hypothetical financial aid system the Form class is already over 1000 lines long, and the developers have decided to draw a Picard Line on it. Not only that, but application forms are only one of many different kinds of forms that the system manages. If the Form class were to contain specialized code for every type of Form it manages, it would grow unmanageably large.

Subclassing is a possibility. But this system doesn’t use Rails Single Table Inheritance, so even if you saved an ApplicationForm it would come back as a plain Form next time you loaded it, and Ruby doesn’t provide any convenient way for us to downcast it to the correct type.

h2. Wrapper Facade

This is a situation where a Wrapper Facade may be called for.

(Note: I got the term form this paper by Doug Schmidt. I believe the pattern described here follows the spirit, if not the letter, of that work.)

It could look something like this:

  require 'delegate'
  class ApplicationForm < DelegateClass(Form)
    def self.create!
      form = Form.create!(:name => form_name)
      first_version = FormRevision.create!(:form => form, :version => 1)
      acceptance_section = FormSection.create!(:name => "Acceptance Criteria")
      rejection_section = FormSection.create!(:name => "Rejection Criteria")
      first_version.form_sections < < acceptance_section
      first_version.form_sections << rejection_section
      first_version.form_signoffs.create!(:name => 'Counselor')
      self.new(form)
    end

    def add_criterion(question_text, kind=:acceptance)
      form_version = current_version # delegated to the underlying Form
      section_name = 
        (kind == :acceptance) ? 'Acceptance Criteria' : 'Rejection Criteria'
      section = form_version.sections.find_by_name(section_name)
      section.form_questions.create!(:text => question_text)
    end
  end

Here we use the Ruby ‘delegate’ standard library to define a wrapper class which will delegate all undefined calls to an underlying Form instance.

Using the wrapper is straightforward, if slightly more verbose than using methods directly on the Form class:

  # To create a form:
  form = ApplicationForm.create!
  form.add_criterion("Do you own an Escalade?", :rejection)

  # To modify a form:
  form = ApplicationForm.new(Form.find(form_id))
  form.add_criterion("Can you count to ten without using your fingers?",
                     :rejection)

h2. Advantages Over Other Approaches

Using a delegate class confers several useful advantages. For instance, it is very easy to construct unit tests that test just the functionality in the wrapper facade by mocking out the underlying Form instance.

  describe ApplicationForm do
    before :each do
      @form = stub("form")
      @it   = ApplicationForm.new(@form)
    end

    it "should be able to add eligibility sections to the form" do
      @form.should_receive(:current_version).and_return(stub("version"))
      # etc...
      @it.add_criterion("Test")
    end
  end

Using a wrapper instead of extending the @Form@ instance with a module means we can selectively override methods in the Form class if needed. Below, we override the @Form#name@ method with our own which appends some text to the name:

  require 'delegate'
  class ApplicationForm < DelegateClass(Form)
    # ...
    def name
      __getobj__.name + " (Aid Application)"
    end
  end

Using a delegate also gives us our own namespace “sandbox” to play in. Any instance variables we use in implementing @ApplicationForm@ will be kept separate from the @Form@ instance variables, so we don’t have to worry about naming clashes.

And, of course, if we ever decide that some or all of the code in the wrapper does belong in the @Form@ class, it is simple enough to move it over.

h2. Conclusion

To sum up, the Wrapper Facade is a useful tool to keep in your toolbox for situations where you want to simplify a particular scenario for a class, without adding any code to the class itself.

Smart Requires in Ruby

I have a lot of Ruby RSpec files that start out with a line something like this:

 require File.join(File.dirname(__FILE__), %w[.. spec_helper])

“This is boilerplate” thought I one day, “my editor should insert this line for me!” But there’s a problem: the line must change depending on how deep in the directory hierarchy the file is found. E.g.:

 require File.join(File.dirname(__FILE__), %w[.. .. .. spec_helper])

This is Ruby, though. Surely there is a concise way to dynamically locate a file in a parent directory? As it turns out, there is. Here’s my solution:

  require 'pathname'
  require Pathname(__FILE__).ascend{|d| h=d+'spec_helper.rb'; break h if h.file?}

OK, it’s two lines instead of one. But the advantage is, now I can insert those two lines into my standard editor template for *_spec.rb files. And it’ll Just Work so long as there is a spec_helper.rb somewhere in the file’s parent directories.

How it works:

  • Pathname#ascend iterates backwards up a file path, successively removing path elements.
  • Pathname#+ joins two path elements using the path separator character (e.g. /).
  • break is called with an argument, causing the block to return the matching path.

TDD Accelerates Development

Periodically, well-meaning Agile advocates will make the argument that practicing Test-Driven Development trades development speed for better quality. That is, it slows you down but it’s worth it because the resulting code is better.

Rubbish, I say. TDD makes me a faster coder.

I could make a number of arguments here about TDD speeding up development in the long-term – TDD cuts down on time spent chasing regression bugs; TDD helps avoid writing code you don’t actually need; etc. And they would all be true and valid arguments.

But I think I can make a case for TDD accelerating development in the short-term as well.

When I started out programming, starting a new project or a new feature was a haphazard process. I’d often start off with “Blank Slate Syndrome” – not knowing where to begin, I’d freeze up for a while considering different angles to attack the problem from. Then I’d make a few tentative stabs at different parts of the program. Often beginning to write one subsystem would lead me to think of something else I’d be “needing”, causing me to leave the current piece half-finished and work on something else. After a few days of chasing these tangents I’d have a bunch of false starts, rewrites, and half-written methods lying around, and no working code.

Learning to practice TDD drastically cut down on my blank-slate issues, because now the question “what next” always had a simple answer: make a failing test pass. If all the tests pass, write a new test. Don’t worry about what you will “need”; just make those tests pass. This alone gave me a huge boost to my initial ramp-up speed in new projects.

Of course, this still left me with the question: what test do I write next? Lately I’ve found that using Cucumber to write acceptance criteria for my apps has all but eliminated this last vestige of Blank Slate Syndrome. When I’m just getting started and I’m not sure where to start writing tests, I step back and write a plain-english explanation of the functionality I want to implement. Then I start at the beginning and start turning each step into runnable code with Cucumber. If at any point I find myself writing non-trivial amounts of code in order to make the step pass, I drop down to the unit level and start writing RSpec expectations (unit tests). Then I move on to the next step, and so on.

The upshot of all this is that I find myself wasting very little time on premature architecture and false starts at the beginning of a project r a feature. And that means real, short-term savings of time.

VirtualBox NAT Forwarding

It takes three lengthy commands to configure a port to be forwarded from the host machine to the guest OS in VirtualBox.  My guess is everyone who uses VirtualBox for any length of time writes these scripts to shorten the process.  Here are mine, in hopes it will save someone some time.

Note that these scripts only work while a VM is stopped.

Damien Katz: CouchDB and Me

One of the most powerful talks delivered at RubyFringe is now available online: Damien Katz: CouchDB and Me

This was one of those “soft” talks that really made RubyFringe special.  Damien got up on stage and bared his soul about what it means to drop everything and work on your dreams when you have a family depending on you.  As a husband and father  it hit very close to home.  I want to be working on cutting-edge technologies – that’s why I moved out of the defense contracting industry and into coding Ruby for a living.  But at the same time, I can’t just drop out, surf couches, and code on The Next Big Thing 12 hours a day.  Every career decision I make affects four other people profoundly.  Coming from this point of view, it was inspirational to hear someone speak honestly and from the heart about wrestling with the same issues.  Highly recommended.

The three line rule

A frustrating couple days of coding has crystalized a new rule for me:

If you can’t demonstrate your new feature in three lines of code, you’re not done.

But it works from the client UI? Great. And it’s fully tested? Super! But you’re still not done.

If it took twenty lines of setup code to make the unit tests work, you’re not done. There should be a close to one-to-one correspondence between artifacts in the UI and artifacts in your codebase. Did you add a new command? There should be a single methodthat encapsulates that command. Did you add a new form? There should be a single classwhich can be instantiated in a valid state with a single constructor or factory call.

I’m not saying this just for the sake of style. This is for your own good. It’s so that six months from now, you can look at that feature on the screen and track it to a single point in the code. It’s so that when you’re training the new guy, you can open up a console and type three lines to demonstrate how that feature works. It’s so that when you write a conference presentation on your brilliant code, you can fit the examples on one slide.

Don’t just be a domain expert; be an API designer. A humane one. The brain you may save from imploding is your own.

I don’t have time to go into technical details, but the Facade pattern is your friend.

Is your keyboard jammed, or are you just writing Haskell?

I’ve been getting back into Haskell lately because I’ve been using the XMonad window manager, which is written and configured in Haskell. Haskell has always held a special place in my heart; I taught myself Haskell by plowing through the ironically-named “Gentle Introduction to Haskell” several years ago, and it taught me more about clean side-effect free functional programming than any amount of Lisp.

A programming language must be considered in the context of its community, and Haskell has an exemplary one. #xmonad is without a doubt one of the friendliest and most helpful channels on IRC, without any of the elite condescension one usually finds on channels devoted to hardcore geek tools like Emacs. I have come to believe, however, that this polite exterior conceals a deep and consuming madness.

I refer to the Haskell community’s addiction to defining operators. Haskell permits virtually any string of nonword characters to be defined as a new operator. This in itself is not a problem, but Haskell programmers seem not to have absorbed the lesson that just because you can, doesn’t mean you should.

To make my point, I call upon Mark Twain, somewhat paraphrased:

In my note-book I find this entry:

July 1. — In the hospital yesterday, an operator of thirteen characters was successfully removed from a patient — a web developer from near Baltimore; but as most unfortunately the surgeons had opened him in the wrong place, under the impression that he contained a stack trace, he died. The sad event has cast a gloom over the whole community.

That paragraph furnishes a text for a few remarks about one of the most curious and notable features of my subject — the length and obscurity of Haskell operators. Some Haskell operators are so long that they have a perspective. Observe these examples:

  • -->
  • < &&>
  • |||

These things are not operators, they are symbolic processions. And they are not rare; one can open an xmonad.hs at any time and see them marching majestically across the screen — and if he has any imagination he can see the banners and hear the music, too. They impart a martial thrill to the meekest subject. I take a great interest in these curiosities. Whenever I come across a good one, I stuff it and put it in my museum. In this way I have made quite a valuable collection. When I get duplicates, I exchange with other collectors, and thus increase the variety of my stock. Here are some specimens which I lately bought at an auction sale of the effects of a bankrupt bric-a-brac hunter:

  • .|.
  • < +>
  • >>>
  • ^>>
  • +++

Of course when one of these grand mountain ranges goes stretching across the LCD screen, it adorns and ennobles that coding landscape — but at the same time it is a great distress to the new student, for it blocks up his way; he cannot crawl under it, or climb over it, or tunnel through it.

[ad#PostInline]