taylorbarstow.com

Rails: Augmenting ActiveRecord::Base#find

Let’s say you want to modify a given ActiveRecord class such that all #find calls will, by default, sort by a given column. I ran into this the other day, and I wasn’t quite sure how to do it. Turns out it’s actually pretty easy (though not 100% trivial for the noob):

class User < ActiveRecord::Base
  def self.find(*args)
    options = args.extract_options!
    options[:order] ||= "last_name ASC, first_name ASC"
    super(*args.push(options))
  end
end

This snippet will cause User#find calls to by default sort the results first by last_name, then by first_name. If, however, you specify the :order option when calling #find, this method will respect your choice.

Caveat: I’m not sure when Array#extract_options! showed up in Rails’ ActiveSupport library, but it’s at least there as of 2.1.0.

Ruby: HTTPClient is was Sloooooow

Update: A new version of HTTPClient has fixed my slowness problems. More info in the comments.

Is this just me? I think it must be—I am getting terrible performance using HTTPClient vs Net::HTTP. I was looking for an alternative to Net::HTTP because its API is ugly as hell, but the performance difference leaves me with no choice.

Let’s take the example of loading this blog’s last four entries using the Google AJAX Feed API. Net::HTTP consistently takes less than a second to load the results, while HTTPClient consistently takes between 10 and 15 seconds! This can’t be right, I must be doing something wrong…

Here’s the script I’m using to test:

require 'httpclient'
require 'net/http'
require 'uri'
require 'cgi'

def time(label)
t_start = Time.now.to_f
yield if block_given?
puts "#{label}: #{Time.now.to_f - t_start}s"
end

feed_url = "http://taylorbarstow.com/feed/"
url = "http://www.google.com/uds/Gfeeds?v=1.0&amp;amp;amp;amp;amp;output=json&amp;amp;amp;amp;amp;q=#{CGI.escape(feed_url)}"

time "Net::HTTP" do
Net::HTTP.get(URI.parse(url))
end

time "HTTPClient" do
HTTPClient.new.get_content(url)
end

A Three Hour Tour

Lesson learned: pay your stupid parking tickets when you get them.  I spent Tuesday morning on a tour of Boston-area parking clerks paying off tickets so I could renew my registration. Well, at least I got some exercise.