A pet peeve of mine is the lack of a documented shortcut in Ruby’s #strftime to function to return the hour of the day, in twelve-hour clock, without a leading zero. To wit:

puts Time.now.strftime("%I:%M") # >> 03:29

That’s not particularly attractive. I could strip the leading zero with some string manipulation, but this is getting sledgehammer-ish to crack a nut. Fortunately, this works:

puts Time.now.strftime("%l:%M") # >> 3:29

That’s a lowercase L in the formatting string, which returns the number of hours in a twelve-hour clock sans leading zero. Result! And yes, that’s undocumented everywhere I’ve looked. Thanks to my colleague Colin for pointing that trick out.

Now, if only I could get it to return am/pm without having to call #downcase

Connecting Rails to legacy databases isn’t actually that hard – depending on the database you start out with. Recently, we needed to perform some statistical analysis on a large Movable Type database. Rather than wrestling with endless SQL queries at the prompt, it made sense to abstract out a little and build some kind of modelled front end to the statistics.

The most obvious tool for me to use was Rails; I’m familiar with it, I like the way ActiveRecord works, and it means that I can poke around the database from script/console if I need to.

The reason this turned out not to be too hard is because whilst Movable Type doesn’t conform to Rails’ opinionated ideas of what a schema should look like, it is still a well-designed and normalised database. Because of this, we can teach ActiveRecord to understand the database.

First of all, we start by creating our models: for our needs, Blog, Comment, Post and Author. We generate them in the usual manner – script/generate model blog. Once we’ve done that, we delete the migration files in db/migrate it creates, because we’re not going to use them.

Next, we point config/database.yml to the Movable Type database.

And then, we build our relationships thus:

class Blog < ActiveRecord::Base
  set_table_name "mt_blog"
  set_primary_key "blog_id"

  has_many :entries, :foreign_key => "entry_blog_id", :order => "entry_created_on"
end

class Entry < ActiveRecord::Base
  set_table_name "mt_entry"
  set_primary_key "entry_id"

  has_many :comments, :foreign_key => "comment_entry_id"
  belongs_to :blog, :foreign_key => "entry_blog_id"
  belongs_to :author, :foreign_key => "entry_author_id"
end

class Comment < ActiveRecord::Base
  set_table_name "mt_comment"
  set_primary_key "comment_id"

  belongs_to :entry, :foreign_key => "comment_entry_id"
end


class Author < ActiveRecord::Base
  set_table_name "mt_author"
  set_primary_key "author_id"

  has_many :entries, :foreign_key => "entry_author_id"
end

The set_table_name method tells the ActiveRecord class what table to look at, and the set_primary_key method does exactly what it says on the tin. (It also makes sure that #to_param works correctly based on whatever our new primary key is, which is handy). Beyond that, we simply have to specify the foreign keys on our relationships and everything plays ball; we can now access blog.entries just as we do with a typical Rails setup. It’s now easy to write the rest of our Rails app – model methods, controllers, views – just as we normally would. We’re just using the MT database to pull out our data.

And if you’re wondering: yes, it made the manipulation a lot easier, and a few hours poking at the console began to yield some interesting algorithms to apply.

Velocity bundle for TextMate

28 September 2007

Well over a year ago, I mentioned that I was working on a Velocity bundle for Textmate. Or, to be more precise: I mentioned that I’d already written one that we were using at NPG.

A year later, I’m ready to release the bundle; you can get it from its Google Code site. But before you go there, an explanation for the delay is in order – and on the way, I’ll tell you about how the bundle was written.

Continue reading this post…

So, this blog (for its sins) is running on WordPress 2.0.5. That’s a bit out-of-date. The main reason is because it has all sorts of jiggery-pokery to make it work the way I want – a tagging solution based on Jerome’s Keywords that was modified when I moved to 2.0; all sorts of template hacking to make the beautiful breadcrumb trail at the top you see work.

I’ve resisted upgrading due to the hell that was hacking plugins and templates into future versions of WordPress. Until now, that is. WordPress 2.3 (finally) introduces a proper tagging solution – entirely separate to the “categories” system. Well, not quite, as we’ll see – but it finally means that the architecture of Infovore.org is now entirely possible within WordPress itself.

Of course, now you’ve got to convert your custom tagging solution to the new schema. I’ve written a small script to do this for myself – only took about an hour, and that’s mainly because I was exploring the schema, and my PHP is a little rusty. Of course, now I know a reasonable amount about how tagging is implemented in WordPress 2.3, and felt I should write this up properly, so that anybody else converting custom tagging solutions might save themselves some time.

Continue reading this post…

It’s fairly common practice in jQuery to bind events to a quick anonymous function that performs the action you desire. But how do you bind an event to a non-anonymous function – something that you’ve already extracted into a function so as to avoid reptition? I learned this one the hard way, and thought it was worth sharing.

I was working on some jQuery to apply to some legacy HTML at work, and was fiddling around to see if our goal was possible.

I was working on a “springy” archive menu. There are some headers and some lists; the lists are hidden on pageload, and when you click on a header, the subsequent list (ie the archive for that year) opens. Many lists can be open or closed at once. In addition, we toggle a class on the header (rather than the header link, which is there purely out of legacy code for now) to change an image, indicating that it’s open.

Here’s my proof of concept code – my first working version to demonstrate how this functionality would work.

$(document).ready(function() {
	var headlinks = $("div.container h3 a");

	for (var i=0; i < headlinks.length; i++) {
		$(headlinks[i]).bind("click", function() {
			$(this).parent().next().toggle();
			$(this).parent().toggleClass("open");
		});              
		$(headlinks[i]).parent().next().toggle();
		$(headlinks[i]).parent().toggleClass("open");
	};

	toggleArchiveLinks(headlinks[0]);
	$(headlinks[0]).parent().next().toggle();
	$(headlinks[0]).parent().toggleClass("open");
});

Now we've got the code working, it's time to refactor. There's a lot of repetition going on - three instances of that "toggle visibility and toggle class" behaviour, so let's pull that out into a function:

function toggleArchiveLinks(element) {
	$(element).parent().next().toggle();
	$(element).parent().toggleClass("open");
	return false;
}

Much better. Unfortunately, we can't replace our anonymous function within that bind directive with this. I initially thought you could bind "click" to toggleArchiveLinks(this). But that doesn't work, because in the context of events, what gets passed out to another function is the event object itself. (I think it works fine in the anonymous object due to the way things are scoped).

But it's a bit ugly to refactor some, but not all of the code. After looking at the jQuery docs for bind, it turns out that there's a third parameter you can pass in: a data object. This is made available to a handler function. So that means we can pass information about the element we want to toggle to a handler event. We write our new bind directive like this:

$(headlinks[i]).bind("click", {element: headlinks[i]}, handleToggleEvent);

That object in the middle will be made available to a new function handleToggleEvent. (We could, of course, pass as many key/value pairs as we wanted to to the function). We also need to write handleToggleEvent. That function looks like this:

function handleToggleEvent(event) {
	toggleArchiveLinks(event.data.element);
	event.preventDefault();
}

The function accepts an event as a parameter, and the object/hash from our bind statement is available as event.data. We're then free to call toggleArchiveLinks on the element of our choosing. Finally, we have to call event.preventDefault in order to stop the event propagating any further. If we don't do this, the bound behaviour will happen, and then the link will click through as normal. return false; won't work here, because we're actually dealing with the event itself, not just an anonymous function.

So we've now managed to refactor some repetitive code and call it from a bind statement. Our final jQuery script looks like this:

$(document).ready(function() {
	var headlinks = $("div.container h3 a");

	for (var i=0; i < headlinks.length; i++) {
		$(headlinks[i]).bind("click", {element: headlinks[i]}, handleToggleEvent);                
		toggleArchiveLinks(headlinks[i]);
	};
	toggleArchiveLinks(headlinks[0]);
});

function toggleArchiveLinks(element) {
	$(element).parent().next().toggle();
	$(element).parent().toggleClass("open");
	return false;
}

function handleToggleEvent(event) {
	toggleArchiveLinks(event.data.element);
	event.preventDefault();
}

Which is much better, I think.

I’ve just had my first patch accepted on an open source project. Quite chuffed with that! As of this weekend, the Rails calendar_helper plugin is now at version 0.21. My changes are very minimal, and only really to do with the markup.

Firstly, the default table markup’s had an overhaul. The date now goes into a %lt;caption> tag, outside the <thead>, as is appropriate. The <th>‘s in the thead now have scope="col" applied to them, again, as is appropriate.

The only other change is optional. If you pass in an option of :accessible => true, any dates in the grid which fall outside the current month will have <span> class="hidden"> monthName</span> appended to them. It could be reasonably inferred that plain numbers are dates that relate to the caption of the table, but the numbers outside the current month should probably be clarified.

You can come up with your own method of hiding content marked as .hidden; at NPG, we use the following:

.hidden {
	position:absolute;
 	left:0px;
 	top:-500px;
 	width:1px;
 	height:1px;
 	overflow:hidden;
}

but really, use whatever you’re most comfortable with.

You can get the plugin from Geoffrey Grosenbach’s subversion:

http://topfunky.net/svn/plugins/calendar_helper/

via the usual Rails plugin installation method.

There comes a point in every developer’s life when your realise the problem isn’t your work, but the tools you’ve got to hand. Toolsmithery is an important part of the job, and so I spent a few hours yesterday crafting a tool useful to any front-end developer.

The result is the CSS Redundancy Checker.

When you’re writing HTML, over time, your CSS files begin to fill up a lot. If you’re working on a large project, you might even end up with several people contributing to the CSS file, not to mention refactoring each other’s work. The result is a directory full of HTML files, and a very large CSS file.

What tends to happen is that not ever selector in the CSS file actually applies to your HTML; many are rendered redundant by refactoring, or by changes in HTML. But when you’ve got a 70k+ CSS file, it’s not easy to check precisely which selectors aren’t in use any more.

Enter the CSS Redundancy Checker. It’s a very simple tool, really. You pass in a single css file, and either a directory of HTML files, or a .txt file listing URLs (one to a line). It then proceeds to look at each file in turn, and at the end, list all the selectors in your css file that aren’t used by any of the HTML files.

That’s it. I’m pretty sure it’s accurate, and it should work with most CSS files. Most of the magic isn’t down to me, but down to _why the lucky stiff‘s marvelous Hpricot HTML parser. The script itself is about 50 lines of reasonably tidy Ruby. You’ll need Ruby, and Hpricot, in order to run it. There’s more full documentation over at the Google Code site where I’m hosting it. Please add any issues there, or get in touch if you want to contribute.

Things it doesn’t do: listing line numbers of where the selectors are. I wrote that functionality on the train this morning, but I can’t find a way to make it 100% accurate, so thought it best to leave it out – inaccurate line numbers are of no use to anyone. If you can come up with a way that works, let me know. Also, at some point I might turn it into a Textmate command. All in good time, though.

The need for the tool came out of a large project we’re working on at NPG, but I felt it would be useful to pretty much any HTML developer. So I’ve released it to the world. Let me know what you think, and do spread the word. You can get it via svn checkout, for now:

svn checkout http://css-redundancy-checker.googlecode.com/svn/trunk/ css-redundancy-checker

Mac OSX 10.4 still only ships with PHP4, which is fine and all, but I eventually bit the bullet and decided to install PHP5.

The most immediately obvious way to do this is with Marc Liyanage’s excellent installer. I unzipped, installed the .pkg, and rebooted Apache.

Except Apache didn’t want to reboot. Apache refused to start, actually. Looked like a potential crisis!

Fortunately, a few minutes of digging found the solution. Pretty obvious, really:

you can’t load both mod_php4 and mod_php5 Apache modules at the same time.

I had mod_php4 enabled already. By commenting out the lines referring to it, Apache started up just fine, running PHP 5. Crisis averted.

As you probably know, when it comes to code (both in and out of work) I’m a Ruby and Rails guy. It’s not necessary to go into much detail “why”: the expressiveness of Ruby and the dynamism and speed of development in Rails are big wins for me.

But it’s not always possible – or practical – to knock out Rails applications for every task, and right now, I need to deploy something in PHP. Something very simple, that doesn’t warrant the deployment overheads of Rails (which we’re all aware of, right?)

Refusing to get caught up in WordPress if at all possible (not going into that again, either), I set out to look for a nice, well-documented, lightweight PHP web framework.

Oh dear.

Continue reading this post…

As a Rubyist and Textmate user, you’ll probably be aware that def will tab-expand to stub out a method definition. You might also be aware that, for the purposes of Test::Unit, deft will tab-expand to a test method beginning def test_, allowing you to append the name of your test.

But that’s not much more help, because if we’re naming our tests properly, they’re probably going to have very_long_names, and hitting underscore all those times is a bit of a pain. So I rectified that, with this command (and it’s a command, rather than a snippet, because of all the processing it does). Pull up the commands dialog (Command-Opt-Control-C), create a new command in the Ruby bundle, and give it the following code:

#!/usr/bin/env ruby

name = STDIN.read.strip
testname = name.gsub(" ", "_").downcase
print <<OUTPUT
	def test_#{testname}
		\$0
	end
OUTPUT

The command’s Input should be “Selected Text” or “Line”; its Output should be “Insert as Snippet”. The scope should be set to source.ruby. And give it whatever key definition you want; I’ve got it on ctrl-opt-shift-t.

Usage is easy. On a new line in your test file, type the name of your test in plain English with no punctuation, eg:

get to index should list all items

and then hit your shortcut. You’ll get the following out:

def test_get_to_index_should_list_all_items

end

and your cursor will be slap bang in the middle of the test, indented, ready to write. That’s what I really want from a test definition snippet – something more than deft supplies. It’s another minute or two’s work to make it strip punctuation, so you can convert real sentences to test cases. I just decided to condition myself to save on coding on this morning’s commute.