Rails tip: Dealing with out of sync migrations
Sometimes, for one embarrassing reason or another (usually involving chaotic branch merges…) a database migration can get leapfrogged. When this happens, it’s tempting to renumber the leapfrogged migration, but that breaks any servers where the migration didn’t get renumbered. Here’s how I dealt with it recently:
class MaybeOldMigration < ActiveRecord::Migration
def self.up
unless old_migration_applied?
OldMigration.up
end
end
def old_migration_applied?
# Checks that the schema looks as it should
# if the old migration got applied
end
endYeah, it’s a hack, but it’s a fairly robust hack.
A quick Javascript formatting tip 10
IE’s a pain. The particular pain I want to write about is its pickiness about Javascript object literals. Consider the following Javascript object:
{ success: function () {...},
failure: function () {...},
}If you’re used to programming in Perl or Ruby, that trailing comma’s perfectly fine, in fact leaving it there is sometimes considered good practice because it makes it easy to extend the hash, just add a new row and leave another trailing comma.
The trouble is, it’s not strictly legal to do that in Javascript. Pretty much every implementation out there will allow it though.
Except IE.
So, I’ve taken a leaf out of Damian Conways Perl Best Practices and writing my object literals as:
{ success: function () {...}
, failure: function () {...}
}By sticking the comma at the beginning of the line, I’m never going to make an object that breaks IE, and adding a new line to the hash is straightforward too. Just stick the cursor in front of the }, type my leading comma, space, attribute name, and hit return when I’m finished.
I’ve also started using the same practice pretty much everywhere else that I’ve got a comma separated list of things:
var foo
, bar
, baz
;
$.each( anArray
, function () { ... }
);It looks weird at first, but trust me, it grows on you.
Update
In the comments, I make reference to tweaking Steve Yegge’s excellent js2-mode to handle leading comma style a little more gracefully. Since then, I’ve made it work and attached a diff to this issue on the project’s issue tracker.
Ads are gone 2
Back when I was writing the occasional “How do you find me?” article, I would get some weird ads showing up. On one occasion, I commented that the searcher had obviously just typed a homework question into google and expected an answer. All the ads on that page ended up being for sites that would write your essays for you.
“Hmm…” I thought, “That’s not good.”, and set about adding those advertisers to the block list.
Then, in another article, I ranted about those, ah, bastions of democracy (thank you, Tom Lehrer) who indulge in comment spamming and found myself advertising them.
Rolling back the enlightenment which discussed, amongst other things, my Uncles’ marriage after 36 years together (yay!) attracted some pretty dodgy ads too.
To my shame, none of these made me rethink the advertising, I just extended the filter and shook my head at the unpleasantness of it all.
The straw that broke the camel’s back was the advertising around Fat is an economic issue ran utterly counter to the spirit of the of the article, and they were like “whack a mole”. Every time I extended the filter, another ad for another bloody health insurance leech or some other snake oil peddler popped up.
So, screw that, the Google ads are gone – it’s not as if they were making me a huge amount anyway. I’ll continue with the left margin Amazon links though – nobody ever buys anything I recommend, but I like the pictures.
Fat is an economic issue 9
Terry Pratchett once observed that a character of his was anorexic because every time they looked in a mirror, they saw a fat person. By that measure, I’m anorexic, though I tend to avoid mirrors. By more objective measures, I’m morbidly obese – 6’ tall, 346 pounds; the Body Mass Index calculation is never going to give a good number.
To listen to some sections of the press, I might as well be public enemy number one. A drain on the public purse, a morally bankrupt insult to the eye of the right thinking, Daily Mail reading healthy public. Apparently, I have the self control of an incontinent puppy and spend my time sat on my arse in front of the TV or looking at child porn on the internet, constantly stuffing my face with lard and chocolate.
Mmm… lard and chocolate…
Now, everyone’s entitled to their opinions of the morality of others. Catch me on another day, and I can rant for ages about the ugliness of the way diet and beauty industries stoke insecurities to sell product. Today I want to talk about the cost issue.
Fat people aren’t cheap to keep – we tend to die younger, and in the process of our dying we cost a lot of money. But dying can be an expensive business and however we go, we all do sooner or later. Fat people’s healthcare costs may well be higher than those of healthy people of the same age, but those healthy people could end up waiting ‘til they are 80 before dying of something horribly expensive like cancer, or Alzheimer’s.
When you add up the net lifetime healthcare costs of the average healthy person, and those of the average obese person, the healthy person costs more.
This is analogous to the “Long Tail” idea – the idea that the long tail of low sales of ‘specialist’ books/records/services adds up to being of greater value than the total sales of the top 100 or whatever. Obvious when you think about it, but running counter to traditional thinking in this area.
We’re really good at spotting the big things, but rather less good at spotting the slow accretion of small things. Each drop of water that falls from a stalactite to a stalagmite doesn’t appear to contribute anything. Nevertheless, the stalactite and stalagmite got there somehow.
I find this knowledge rather heartening. Okay, so as a fat git with diabetes, I’m likely to die young, but that’s my business. The pernicious idea that the broader population of tax payers is somehow suffering because of me and that because of that I should be denied access to health care isn’t just morally repugnant, it’s economically illiterate.
References
Lifetime Medical Costs of Obesity: Prevention No Cure for Increasing Health Expenditure from PLoS medicine. The paper describes a mathematical model rather than something which does the arithmetic on a real population, so it’s only as good as the assumptions, but it does seem compelling that the driver for high total healthcare costs over a lifetime is the length of that life. But, as I fat git, I might be expected to say that. Ho hum.
Reinventing the wheel for fun and profit
When they tell you to stop because you’re reinventing the wheel, ignore them and carry on building a better mousetrap.
Code is data, and it always has been 3
I’m just back from the first Scotland on Rails conference, and a jolly fine conference it was too. Much kudos is due to Alan, Graeme, Abdel and Paul. It was hard to believe that this was the first conference these guys have run and I think all my fellow delegates hope it won’t be the last. As I said in the Pub on Saturday night, I’d had a talk proposal knocked back and, in that situation, it’s terribly easy to find yourself sitting in a session thinking “Bloody hell, my talk would have been better than this!”, but not at this conference.
A phrase that cropped up a couple of times was the old saw that “Data == Code” – it’s very hard to avoid the idea once you start talking about code generation or Domain Specific Pidgins, parsing… I first came across the idea in The Structure And Interpretation of Computer Programs where it’s elegantly phrased as “Data is just dumb code, and code is just smart data”. Traditionally, the idea seems to be attributed to John McCarthy, the inventor of Lisp. But it’s older than that. Way older than that. The idea is actually older than Computer Science. It lies at the core of Turing’s original paper On Computable Numbers, with an Application to the Entscheidungsproblem in which invents computer science on the way to proving that it’s impossible to decide algorithmically whether a given statement of arithmetic is true or false.
In the course of the paper, Turing posits what has become known as the Halting Problem:
Given a description of a program and a finite input, decide whether the program finishes running or will run forever, given that input.
Turing’s proof runs something like this:
Suppose we have a subroutine halts?(code,data) which solves the halting problem. Let’s use that to write something like:
def counter_example(code)
if halts? code, code
for (;;)
end
else
return
end
end
counter_example(File.read(STDIN))and ask the question “What happens when we run counter_example.rb < counter_example.rb”? If halts? reckons that counter_example would halt, given itself as input, then counter example will enter an infinite loop, but if halts? reckon that it would enter an infinite loop, then it would halt. Which is a contradiction. Which means that there can be no subroutine halts?, which means that maths is hard enough to be interesting and occasionally undecidable.
Look at how the proof works – it’s built around the idea that code can be treated as data. In fact, you could say that the Turing Machine looks like it does because Turing was working backwards from this core idea to describe a sufficiently powerful machine that could obviously treat it’s own description as data. Certainly when you compare the clarity of his proof that the halting problem is undecidable (given the idea of the universal Turing machine) with the contortions required to make mathematics swallow its own tail in similar fashion so that Gödel could prove his Incompleteness Theorem.
So, if you want to know who the idea that code is data is due to, the answer (as is so often the case in our field) is Turing.
Postscript
Incidentally, Turing is also responsible for the first ever bug – his original implementation of a Universal Turing Machine has a couple, one of which is probably a dumb typo (which even I could spot when I read the paper). Another is more subtle, but still fixable. Somewhat delightfully, a young grad student, (Donald W Davies, who invented packet switching) spotted these bugs and told Turing:
I … found a number of quite bad programming errors, in effect, in the specification of the machine that he had written down, and I had worked out how to overcome these. I went along to tell him and I was rather cock-a-hoop … I thought he would say ‘Oh fine, I’ll send along an addendum. But in fact he was very annoyed, and pointed out furiously that really it didn’t matter, the thing was right in principle, and altogether I found him extremely touchy on this subject.
Nearly fifty years later Davies wrote and published a debugged version of the code, which you can find in The Essential Turing. One lesson to draw from the above is that getting annoyed at people pointing out trivial bugs in example code is also at least as old as computer science. Rather splendidly, there’s also a story of the chap who wrote the first ever assembler getting a serious telling off from Turing because the computer’s time was too valuable to waste it on converting symbols into machine code when humans were perfectly capable of doing it themselves. Who knows, maybe Turing’s contention was actually true back in the days of the Manchester Baby…
Tragedy
There’s always a moment, in a perfect tragedy, where you dare to hope that maybe the heroes are going to break the surface tension of the plot and escape. That perfect moment in Romeo and Juliet where, no matter how often you’ve seen it, you hope that this time, Juliet’s message will reach Romeo. Or, when watching Cruel Intentions, you find yourself hoping that the writers have managed to wangle a happy ending.
It never happens of course, and we’d be disappointed if it did. We are taken to the critical point, when everything seems possible, when the characters are pushed to their utmost… and fail. Give me the life and death struggles of two teenagers for whom love is everything and life isn’t worth living without it over the pat solutions of the Dream, or give me “Fortinbras, knee deep in Danes” over the cross dressing, weddings and cruel taunts of Twelfth Night. (Not that I don’t enjoy the comedies).
What brought this one?
Why am I musing on tragedy instead of code?
The explanation is simple: I just watched the last ever episode of The Wire.
If you follow the show yourself, nothing more is needed. If you don’t, why not? Okay, so if you’re in the UK you’re reduced to paying the Murdoch tax, buying the DVDs or watching through Bittorrent (and only Bittorrent is up to date), but you should. All five seasons of The Wire add up to being the best thing I’ve ever seen on television. It’s impossible to describe how good it is without misrepresenting the whole. It’s the kind of campaigning documentary fiction which would make Dickens or Mrs Gaskell proud. It’s a sprawling epic with a huge cast of fascinating and flawed characters. It’s the story of how a cop destroys his career, a junky kicks his habit, a school system fails its pupils, politicians fail their constituents, a newspaper fails its readers and how a policy of prohibition fails a country.
Prohibition and its consequences are shot through the fabric of The Wire. It’s easy to see how drugs destroy addicts. Easy (for liberal old me at least) to see how the money spent in the War on Drugs could be spent more effectively. What’s not so easy, and what The Wire does so well, is to show how “the game” destroys generation after generation of the best and brightest of the urban poor too. Why bother working to get to college, or getting a regular job when selling drugs is so easy and so profitable? If you’re going to jail for selling the stuff in the first place, why scruple to put a bullet in the head of a business rival, witness, or some mope who calls you a coward? How many “mute, inglorious Miltons” end up dead and decaying in a walled up vacant, or stuck behind the barbed wire of the state pen serving out their natural lives with no hope of parole?
And what does putting them away achieve? For every small victory, we’re shown a corresponding fall. New characters slot into the rôles they have vacated and the cycle begins again. It’s a perfect tragedy – the game is still rigged and only the players change. The gods are unmoved by the struggles of poor mortals, the lawyers get richer, incompetence is rewarded and money is siphoned away from the streets into the pockets of rich white men who already have plenty.
Welcome to Baltimore. Have a nice day.
Javascript scoping makes my head hurt 13
Who came up with the javascript scoping rules? What were they smoking. Here’s some Noddy Perl that demonstrates what I’m on about:
my @subs;
for my $i (0..4) {
push @subs, sub { $i }
}
print $subs[0]->(); # => 0;Here’s the equivalent (or what I thought should be the equivalent) in Javscript:
var subs = [];
for (var i in [0,1,2,3,4]) {
subs[i] = function () {
return i;
}
}
alert subs[0]() // => 4What’s going on? In Perl, $i is scoped to the for block. Essentially, each time through the loop, a new variable is created, so the generated closures all refer to different $is. In Javascript, i is scoped to the for loop’s containing function. Each of the generated closures refer to the same i. Which means that, to get the same effect as the perl code, you must write:
var subs = [];
for (var shared_i in [0,1,2,3,4]) {
(function (i) {
subs[i] = function () {
return i;
};
})(shared_i);
}
subs[0]() // => 0Dodgy Ruby scoping
I had initially planned to write the example “How it should work” code in Ruby, but it turns out that Ruby’s for has the same problem:
subs = [];
for i in 0..4
subs << lambda { i }
end
subs[0].call # => 4Which is one reason why sensible Ruby programmers don’t use for. If I were writing the snippet in ‘real’ Ruby, I’d write:
subs = (0..4).collect { |i|
lambda { i }
}
subs[0].call # => 0My conclusion
Javascript is weird. Okay, so you already know this. In so many ways it’s a lovely language, but it does have some annoyingly odd corners.
Baby's first screencast 9
If you follow the Ruby blogs, you will probably have seen a bunch of programmers attempting to do something akin to Haskell’s maybe, or the ObjectiveC style, message eating null.
Generally, by about the 3rd time you’ve written
if foo.nil? ? nil : foo.bar
...
endyou’re getting pretty tired of it. Especially when foo is a variable you’ve had to introduce solely to hold a value while you check that it’s not nil. The pain really kicks in when you really want to call foo.bar.baz. You can end up writing monstrosities like (tmp = foo.nil? ? nil : foo.bar).nil? ? nil : tmp.baz (actually, if you were to write that in production code, you probably have bigger problems). One option is to just define NilClass#method_missing to behave like its Objective C equivalent, but I’ve never quite had the nerve to find out how that might work. I wanted to write
if maybe { foo.bar.baz }
...
endand have nil behave like an Objective C nil for the duration of the block, but no longer. So I wrote it. Then I thought about how to present it. I wrote the thing test first using rspec and the whole thing just flowed, but writing up a test first development process for a blog entry is painful, so I’ve made a very rough (but blessedly short) screencast of the process instead.
That’s a slightly reduced thumbnail, the movie is substantially more readable. The bottom pane of the window is the output of autotest rerunning the spec every time either the spec or the implementation changes. The top pane alternates between the specs and the implementation. Generally, every time I edit the specs, a test starts failing and every time I edit the implementation it starts passing again. In the (any) real coding run, there were of course false starts, but generally the specs kept me pretty straight.
A word or two of warning: This is a completely unedited, silent, screen cast, there are typos, backtrackings and other embarrassments. I stopped recording once I’d got 4 tests passing, but this is far from release quality (it’s perfectly usable if you know its limitations, but it’s not entirely robust).
Please let me know what you think of this. I’m aiming to make a more polished version, complete with voice over and it would be good to know which bits are confusing and need addressing in more detail in the voice over.
I am not a rock star 16
I am not a rock star. I am a computer programmer. I think I’m quite a good one.
You are not a rock star either.
387,000 matches to that query. Can we all just… I don’t know… grow up please?
Mutter… grumble… chunter… I’m 40 you know!
Updates
I have it on reliable authority that James O’Kelly is a Ruby on Rails Rockstar that would make a great addition to any team!

