
ajax analysis api apple apps atom automator backpack browsers camping capistrano cheatsheets code console design editors ergonomics fluid fowa games gems google helipad hpricot internationalisation javascript lies littlebigplanet mac marketing optimisation patterns performance personal php plugins productivity programming projects prototype rails rapidrails rsi rss ruby server sms snippets ssb standards sysadmin terminal testing textile textmate theory tips tools vim workshops writing xslt
DHH wrote this: Myth #2: Rails is expected to crash 400 times/day – a response to a myth about Rails processes regularly needing restarts.
I’m a big Rails hacker, it’s 90% of what I’ve done for years. I’ve designed and developed these apps: Tiktrac, Ebiwrite, Helipad, Deadline, Loom and Reuters Real Estate, this blog, not to mention work for smaller clients I …

Here’s an idea I’ve been playing with today: Captor, a GUI for Capistrano management. It’s a very rough prototype right now.
Goals:
Caveats:
I recently posted my top 5 uses for Capistrano over at Helicoid Insider—including juicy code snippets!
I like Capistrano a lot. It’s now doing all kinds of things to ease my workflow, from backing up servers to providing me with detailed signup statistics for each of my web apps. Whilst I’m still the only developer designing and building 4 successful web apps I need all the help I can get, so I’ve naturally cobbled together a range of software techniques to help….
I’ve just finished writing an article about how I built a single-sign on server in Rails:
Building our centralised authentication system
It was actually an incredibly rewarding experience. I’ve written up design notes, rationale and provided tips on avoiding problems.
Here’s a JavaScript snippet intended for Rails that I just posted over on my company’s technical blog. It displays the error message for each field when you click on the field, making it easier to see exactly what went wrong when saving a record.
Read it here: Dynamic Rails error help

I just posted this article to my company’s blog: Analytics with Capistrano
If you want realtime stats on your web site, why not try using Capistrano to collect data and create graphs and tables? It’s pretty easy to do this, and the beauty is you don’t need to make any modifications to your application.

Changes is a fast and friendly diff tool. You can quickly list files that have changed in a project, and view differences between files. It also works with Subversion and Git (and several other version control systems), so it will fit right into your typical workflow. Oh, and it also has a TextMate bundle.
Changes gets perhaps the highest accolade for a mac application: I like Changes so much it actually has a permanent place in m…
Welcome to Rapid Rails Part 3: Desktop mastery, the third article in my series focussing on making Rails (and yourself) faster.
A good programmer recognises when to reuse and therefore reduce code. A great programmer applies this tendency to their own workflow. Whether you use an IDE or text editor, working with Rails can be made more pleasant and efficient by observing commonly performed tasks and simplifying them.
The examples given below have a heavy bias toward TextMate, Vim and Mac OS. If you work in Windows or Linux, at the very least consider the following 10 ideas.
This is part 2 of the Rapid Rails series. Part 1 featured tips on how to work more efficiently with Rails by making the most of the bundled and related command line tools. This part discusses how to make your Rails application perform faster, with particular focus on server optimisation. Why? Because systems administration requires a very different skill set to programming, and I’ve been often been expected to manage sysadmin tasks on my Rails contracts—and I bet you have too!
I’ve included real-world e…

Rapid Rails is a series of articles containing succinct tips to increase your productivity when working with Ruby on Rails. This is the first part, and shows you how to make the most of the command-line tools that come with Rails.
The Rails generator script (found inside an application’s directory at script/generate) allows you to quickly create templates for anything you need within Rails. As well as models and controllers, you can also use it to write entire migrations:
scr…
This article is an introduction to testing Rails plugins. It’s a relatively lengthy post, so if you’re reading this in an RSS reader flag it and come back when you’re not too busy. It follows the “taxonomy” style of my previous plugin article, A taxonomy of Rails plugins, where examples are used from open source software.
Knowledge of both unit and functional testing is assumed. The following topics are covered:
There are now almost 1000 entries in the main resource for Ruby on Rails plugins, Agile Web Development’s Plugins Directory. Of these, 596 have repositories listed that are accessible. I wanted to see how many of these plugins came with some form of tests, so I created a spider (using a web spider library) and performed some basic analysis on each repository.
After reading a few magazines, and watching two entire TV shows, the spider came back with a result: 54% of the plugins have tests.
It’s amazing to …
Start using Test Driven Development today is a post I wrote over on my company’s blog. It covers how TDD has improved my work since I started Helicoid Limited, and how you can start using TDD right now.
Despite leaving it for a while, I’m going to continue my previous article, “A taxonomy of Rails plugins”, relatively soon. I’ve been inspired by the excellent plugins by errfree and come up with a few ideas of my own during the heavy workload of 2007. In particular, I’d like to clarify testing Rails plugins. But more of that in the near future.
For now, have a look at 10 essential ruby gems. It’s hosted on my company’s new blog, where you’ll eventually find more articles by me with a greater emph…
A common stumbling block for Rails developers is learning the basics required to write plugins. This is made more complicated by the fact that Ruby is inherently dynamic and offers many techniques for code reuse. Luckily, if you can write Rails applications you can write plugins by simply drawing on a handful of basic patterns.
The purpose of this article is to demystify writing plugins using examples of common patterns used by popular plugins.
Writing a plugin will:

Boards of Canada wrote a song called Constants are Changing. In Ruby even constants are dynamic, holding a reference to an object rather than the object itself. This consistency makes modifying constants possible, and rather than being something considered distasteful it may form an integral part of the design of a system.
Changing a constant’s reference will result in a warning, but there are times when ignoring these warnings might be arguably legitimate. I wrote a simple tool that runs for long periods of time, and …

Have you ever been working on a project that has session variables controlling important aspects of functionality? When they start falling out of controllers and views into a big pile of soup on the floor it’s probably time to encapsulate them.
Although relying on the session object in controllers and views is relatively easy to understand, you should be very wary when you’re tempted to use them this way. Thinking, “I’ll just add a session variable for this” will probably lead to misunderstandings or bugs later on. And on…
Writing test code isn’t easy at first, and writing good test code is even harder. I’ve reviewed several tools to help write better tests here, focussing on ruby.
Code coverage tools attempt to analyse how much of your code has been tested. Reports are generated based on your test code, with columns expressing how much code has been tested.
Incentives for using code coverage tools are:
‘Push Back’ is a simple concept succinctly explained in 37signals’ book, Getting Real. When translating requirements into code, issues often crop up that make implementation impractical. Something about the structure of your project resists a new feature.
Getting Real suggests ways to mitigate push back. I’m going to explain how to spot push back occurring in your code.
Methods or variables become hard to name
If you’re having issues naming things, perhaps you don’t fully understand the problem you’re trying to solve. If the concept is ill-defined,...
Have you found that any of your Rails projects get hits to controller methods that expect parameters? A neat way of handling this is the ActionController::Verification module.
By adding calls to verify in your controller, you can elegantly catch all kinds of unexpected but reasonable uses of your system: from mistyped URLs and browser history auto-complete to web crawlers blindly following links. This way, you can redirect people somewhere logical instead of flashing them with an error message.
You can even insert a message into the flash:
verify :params => “user”,
:only => ...
Have you ever tried concatenating your JavaScript and CSS files for performance improvements? The idea is that latency is a bigger issue than file size when loading web pages, so stuffing all your JavaScript into a monolithic file for deployment should improve performance.
I wrote a rake task to do this for some of my applications (such as tiktrac). This is slightly more cumbersome than a feature I spied in the ActionPack changelog:
Added caching option to AssetTagHelper#stylesheet_link_tag and
AssetTagHelper#javascript_include_tag [DHH]. Examples:
stylesheet_link_tag :all, :cache => ...
With hpricot you can do anything!
puts ((Hpricot(open(URI.escape(“http://www.google.com/search?q=#{term}”))))/”a.l”).collect { |link| ”#{link.innerHTML}: #{link.attributes[‘href’]}” }.join(”\n”)
I needed a quick way of exporting data as zlib from a controller in Rails, so I came up with this:
def export
send_data compress_string(Document.find_all.to_xml), :filename => 'backup.xml.gz'
end
def compress_string(data)
gz = Zlib::GzipWriter.new(StringIO.new(''))
gz.write data
gz.close.string
rescue
gz.close
raise
end
Another way would be to use tempfiles with Tempfile—I wanted to benchmark and profile using files compared to StringIO, but that’ll be an exercise for another day.
This could also work nicely with Minitar.
Imagine your own little mac os app written with the Camping framework, that you can easily share with other mac-weilding friends. It’s all possible with next to no ridiculous hacking at all!
All you need is Platypus. Set it up to create a ruby app that outputs to a text window. Click on “advanced” and select “remain running after completion”, then create the app. Take a look inside the application folder at the script it creates at the script:
YourApp/Contents/Resources/script.
Coaxing the old version of ruby supplied with mac os into running Camping and its required ge…
I’ve created quite a few Rails projects over the last year, some commercial projects, and others are applications released under Helicoid. Here’s a few things I’ve found save time and help make projects as maintainable as possible.
Named routes
You can refer to routes in your forms and links like this: document_edit_url(:id => document.id). Isn’t that much nicer than other means? It can often make code easier to understand quickly, thus helping maintainability.
To use named routes, instead of the usual map.connect directive, use map.my_name.
Migrations
I use migrations for…
This JavaScript class requires Prototype. It displays help on Textile next to elements with a particular class, and parses the help from a Hash that you can define in the constructor.
I’ve been using it to add help next to textareas that accept textile. All I have to do is create textareas with the class “show-textile-help”, and they get a little div full of useful information. The help text is hidden until the user clicks on the link:
AFTER A CLICK BY THE INTRIGUED USER:
Style it a little bit like this:
’ + element1 + ’’
})
textile_help += ’’
})
...
Sometimes you need to display collated data on a page. For example, Basecamp has a useful dashboard which displays all the latest activity across all your projects. I’ve been working on an application that provides Basecamp access to mobile devices, and I realised that reproducing this dashboard would be far too API-intensive to be usable.
It can take anything from 20-1000ms to complete a request using the API, depending on the number of hops the request goes through over the network and how fast the application at the other end responds. So if you want to gather the data Basecam…
I’ve been working hard to improve the performance of Tiktrac, just because it’s been in beta for a few months and I’m really sharpening it up to finally stump up the cash for some serious hardware to run it (and other) applications on.
When I need to improve performance in a rails app, I start off with a few basic questions:
At this point, I start loading slow pages and watching the logs. The logs will show you interesting data like this:
Rendered sheet/_she…
I don’t see much use of anonymous functions in php, yet when I write python or ruby, I use constructs like this quite often. You can do it in php though, with create_function. It’s nothing that fancy, it just lets you create a function whenever you feel like it. This can be placed wherever you need a callback in php.
Callbacks in php must be a function name. You can’t refer to methods in the current class, or hack it by making a function that returns an object: function()>probably_a_singleton>hello(). This is where create_function() comes in.
Here’s an example:
$where_sql[] = ” $...
TextMate is one of the best text editors for Mac OS X. There’s a few features that you might have missed if you’re a new user, which I’ll briefly illustrate with screenshots.
mate .
In the Terminal, type ‘mate .’ to create a project out of the current directory. This is so handy and fast:
Screenshot
cmd-t
Press cmd-t to search through the files in the current project, select the file and press return to open it in a new tab.
ctrl-escape
Press ctrl-escape to call up the bundle menu. This basically lets you process text, you can do handy things like quickly insert language control…
At my company, we’ve been interviewing people for a web developer position, with particular emphasis on programming. Something I’ve noticed is a lot of developers say: “I know JavaScript.” So a simple question I devised for testing this was, “how would you debug JavaScript?” You’d be surprised how many people don’t know the answer to this.
So, if you’re a php/perl/python/ruby/asp/etc programmer who “knows” JavaScript, here’s a few tools to help with debugging. These are Firefox extensions.
View Rendered Source Chart - I can't live without this, it allows you to view the html th...
There’s a few little touches I like on sites I frequent: sensible tabindexes for forms, accesskeys and so on. Once I learn the accesskeys, I can fly around the main sections of a site. I apply these things to the sites I build, and the other day I realised adding accesskeys and supporting markup was no fun at all.
I wrote this JavaScript function to search for all your accesskeys and add some friendly markup. It even detects if the user is running Windows or Mac OS, to tell them to use ‘alt’ or ‘ctrl’:
function underline_accesskeys()
{
var links = document.getElementsByTagNam…
If you wanted to develop a Google Home module that accesses a service using a password, you might notice a few flaws:
There isn’t a password type available, so any user preferences that require a password will display the password in plain text.
If you still want to store passwords in user preferences, be aware that every single time Google Home loads, it will fetch the module with the password in plain text in the GET request.
It would be nice if Google introduced a ‘password’ type, to compliment the existing types for preferences. This would at least allow you to have a starre…
It didn’t take me long, and I knew I wouldn’t be able to go for a few hours without writing a basic plugin for Google Home.
I always wanted to have a del.icio.us search box in a panel with my latest bookmarks, so I wrote this:
Once you’ve added it to your homepage, you can enter your delicious username, and it displays your latest links using raw JSON:
_IG_FetchContent('http://del.icio.us/feeds/json/' + prefs.getString('username') + '?raw', function (responseText)
{
posts = eval('(' + responseText + ')')
for (var i=0, post; post = posts[i]; i++...
A few applications I’ve been developing recently have either had things from script.aculo.us applied for fun, to add effects our client would like, or they’ve been designed with Ajax and visual effects from the start.
A very beta application I’m working on is Multitap.net. Since it’s my project, and I don’t have clients to answer to, I’ve done whatever the hell I want with it. I had these things in mind when creating it:
I went to the Get Started Using Ajax workshop with Thomas Fuchs in London yesterday, and despite having used minimal Ajax and script.aculo.us effects before, learned quite a lot.
Thomas started off discussing the background of the technology, and wasn’t scared to dive into real examples, with PHP and Rails. He explained how the Ajax call works, and also discussed the pros and cons of using JavaScript libraries, such as Dojo and script.aculo.us, against using more lean server-oriented abstractions such as Sajax.
What was very interesting was his section on real world examples. The pr…
I had a User class, which then had a Moderator class. I was using the “type” field in my database to denote whether a user was a User or a Moderator. However, my validations weren’t working as I expected:
validates_as_unique :name, :email
Users could have the same email address as Moderators. Obviously sometimes this kind of scoping makes sense for STI classes, but it doesn’t here. I ended up writing this:
module ActiveRecord
module Validations
module ClassMethods
# Intended for use with STI tables, helps ignore the type field
def validates_overall_u…
I often annoys me when people don’t make it clear what they’re referencing in an article. Sometimes people don’t give any references at all, and when they do they use links on words that shouldn’t be links (the click here syndrome).
So I wrote this Javascript to help out. It adds a section at the bottom of each of your Wordpress posts containing all the links you referred to in a post:
/* From Prototype /
document.getElementsByClassName = function(className) {
var children = document.getElementsByTagName(‘‘) || document.all;
var elements = new Array();
for (var i =...
We have a PHP CMS with a lot of poorly written HTML in the client-contributed content. This kept causing my XSL template system to output XML errors. I got around this problem by:
Using CDATA tags around unpredictable HTML helps prevent problems with the XML parser. Without the final step, the resulting HTML …
Textile provides a simple way of writing human-friendly text that can easily be translated to XHTML. HTML tags are simplified into a set of phrase and block modifiers; even tables and attributes can be created.
I was looking at the PHP code for this and wondering if I could create an XSL file that could translate similar text into XHTML. I created some XML to contain my text:
And then used the following recursive algorithm to process it in XSLT:
...
I often use a message class for a lot of things with PHP. This allows me to build messages to display to the user for errors, successes and general feedback.
Classes for each of these three things are created in CSS to display the information, and then I use a simple PHP class for appending messages to a arrays.
I wanted to include this in some XML data I was processing with XSLT, but I found it difficult to combine multiple XML files with PHP’s XSLT processor. However, in PHP4, you can do it like this:
// this is a code fragment
//
$XML = implode('', file($XML_Fi...