Persisting a Country Selection in Rails Using country_select

Posted at 4:18 PM on July 22, 2008

Rails’ country_select form helper doesn’t accept a :selected option. If a validation error occurs, you really don’t want to force the user to reselect a country. However, there’s no documented way of persisting that data when re-rendering an unvalidated form.

Fortunately, the country_select helper accepts a parameter called priority_countries. This exists so you don’t have to scroll all the way down past Uganda and Ukraine just to arrive at the good ol’ US of A. A clever workaround to this problem is to use the priority_countries parameter to effectively “select” the previous value through a bit of magic.

<%= form.country_select :country,
  [@location['country'] || 'United States'] %>

This ERb line merely appends your selected country to the top of the priority country list. And, indeed this allows your old country to remain selected even if a validation errors causes the form to be rendered again.

Monkeypatching For Robots

Posted at 6:27 AM on July 16, 2008

Even though Jeff Atwood believes that monkeypatching will lead to the apocalypse, I’ve discovered three cases where it has proven to be most useful.

Case 1: Dynamically Patching a Plug-in

Let’s face it. The Ruby on Rails wiki is littered with a cadre of unmaintained plugins. One example is file_column. Attachment_fu pretty much replaces this, but for whatever reason, the project that I’m working on is using the old warhorse of file upload packages. Recently, I’ve noticed several problems with file_column. The biggest issue is that it was written pre-Rails 2.x. So, file_column doesn’t support the new asset_host feature. Combining monkeypatching with the Rails alias_method_chain allows us to patch the underlying code with minimal effort. And, keeping the dynamic patch separate, means that updating the plugin will not overwrite the patch.

# Rails lib/project_system.rb
module FileColumnHelper
  def url_for_file_column_with_asset_host(object, method, options=nil)
    ret_url = url_for_file_column_without_asset_host(object, method, options)
    unless ActionController::Base.asset_host.blank? and RAILS_GEM_VERSION[0,1].to_i >= 2
      ret_url = ActionController::Base.asset_host + ret_url
    end
    ret_url
  end

  alias_method_chain :url_for_file_column, :asset_host
end



Case 2: Adding a Feature to a Plug-in

I’m a total Unix snob. Upper-case filenames injure what’s left of my dwindling sanity. File_column recklessly allows the user’s filenames to be saved directly to the filesystem. This has the side-effect of dumping a flagon full of mime-type detection FAIL when you view the files that have been uploaded to the server. Think of users uploading images named me.jpeg, me.JPG and me.Jpeg. Inconsistent capitalization is clearly evil and has to be sanitized before it gets to our precious disks. Using a monkeypatch with alias_method_chain, you can override file_column’s sanitize_filename method to convert the filename to lowercase.

# Rails lib/project_system.rb
module FileColumn
  class << self
    def sanitize_filename_with_downcase_rules(filename)
      self.sanitize_filename_without_downcase_rules(filename).downcase.gsub(/\.jpeg$/,'jpg')
    end
    alias_method_chain :sanitize_filename, :downcase_rules
  end
end



Case 3: Overriding a Native Ruby Class to Facilitate Symbol#to_proc Abuses

Ever since reading Reg Braithwaite’s (1..100).inject(&:+) post, I’ve been mystified and rather infatuated with Rails’ Symbol#to_proc method (which, incidentally, was only possible through Rails’ monkeypatch to the Ruby Symbol class).

Recently, I wrote a method to detect whether any one checkbox or radio button had been selected on a HTML form. This would serve as a form validation, but was complicated due to the fact that radio button values are arbitrary strings and checkbox values are posted as “0″ and “1″. The radio button values had to be converted to boolean by the controller, but ActiveRecord’s value_to_boolean method does not support this. Monkeypatching came to the rescue yet again and allowed me to override Object in an inject-friendly way.

# Rails lib/project_system.rb
class Object
  def selected?
    return true if self and self.is_a?(String) and self.include?('location')
    ActiveRecord::ConnectionAdapters::Column.value_to_boolean(self)
  end
end

Rather than writing a massive case statement or nested if/elsifs, we can just write the following in a model.

# Rails app/models/model_name.rb
def selected_place?
  places.collect(&:selected?).inject(&:|)
  # Logically, the same as places.collect(&:selected?).any?
end

The preceding loop calls our new Object selected? method on each of the location_types column, and the inject ORs all the data together.

I don’t really understand why Jeff is writing these slime pieces on monkeypatching. Jeff’s logic is equivalent to reasoning that driving should be outlawed because cars are dangerous. However, just because a few people drive drunk doesn’t mean that no one should drive! Oddly, I would get behind a law to make drunken monkeypatching a felony.

Malfeasance in 64-bit PowerPC MySQL Gem Compilation

Posted at 8:25 PM on May 12, 2008

For the three people in the world building the Rails mysql gem on a PowerPC G5-based OS X Server with the 64-bit MySQL installed getting this crazy error:

lazy symbol binding failed: Symbol not found: _mysql_init

The magic ninja gem install command that will cure all your ills goes a little something like this:

sudo env ARCHFLAGS="-arch ppc64" gem install -V mysql -- --with-mysql-include=/usr/local/mysql/include/ --with-mysql-lib=/usr/local/mysql/lib --with-mysql-config=/usr/local/mysql/bin/mysql_config --with-mysql-dir=/usr/local/mysql

Pretty obvious when you think about it. Not sure why it took me a little over an hour to discover the crucial lynchpin for correcting this system-wide thought-tastrophy.

Words of Wisdom From The Professor of Magic

Posted at 10:02 PM on April 24, 2008

The Professor of Magic is the preeminent technological luminary of the new millenium. As an astute observer of the human condition, connoisseur of fine wine and spirits, raconteur, and master of the mythical yellow ball, his knowledge of the universe is beyond all comprehension. After an hour in the gym today, the endorphin rush inspired him to bestow the following wisdom unto me.

Hoyhoy: I used to think reading blogs was like giving the middle finger to traditional media, but now I’m not so sure.
Professor of Magic: Consider cereal. There’s 5,000 brands, and they’re essentially composed of food coloring and 90% sugar. Blogs are like cereal because most of them exist in a homogeneous intellectual wasteland.
Hoyhoy: Sure, you have the odd box of Grape Nuts (The New York Times), but I suppose the majority of blogs are nutritionally bankrupt like Cookie Crisp (Involution.com).
Professor of Magic: Right.
Hoyhoy: Facebook is worse than the blogs though. It’s turning the Internet into television. Except, instead of preying on people’s boredom and loneliness like the teevee, Facebook exploits their vanity. Basically, the Jerry Springer Show was the read-only version of Facebook.
Professor of Magic: And, Facebook apps are the equivalent of ringing somebody’s doorbell and running away.
Hoyhoy: Good point.
Professor of Magic: Blogs and social networks are just a waypoint before we reach the eventual conclusion of hooking wires directly into the heads of the superfluous population.
Hoyhoy: Not for me. I took the blue and red pills simultaneously.

Eugene Mirman’s Application for “Cupid”

Posted at 2:14 AM on February 12, 2008

Height: 6000-inches (aproximately two earth years)
Nicknames: Ace and Dr. Bathroom
Name of Employer: United League of Underwater Nations
Position Held: Surgeon General of a Place I Made-up
Do you drink alcohol?: YES!
If so, how often: Once a day, for 8 hours
Where do you usually meet women: In hotels or the street
Do you enjoy dating: NO!
What is the most romantic thing you've done for a girlfriend?
Shot a dog that was attacking her.
What's the most adventurous date you've ever arranged for a woman?
An expedition to the center of the earth.
What do you want out of your next relationship with a woman?: POWER!
List the qualities you find most attractive in a woman: TELEVISION!
Describe your ideal woman.
From the mountains, is new to technology, and thinks I am MAGIC!
Why would a woman have fun on a date with you?: I would let her punch me.
How important is sex to you in a relationship?
Not at all in the first few minutes.  Then, CRUCIAL over the next 20.
What do women find most attractive about you?: I AM FAST AT SEX!
Do you have a strategy for standing out in a crowd?: KARATE!
Describe situations where you have treated a girlfriend in a way you regret.
I once killed my girlfriend's dog.

All Hail Salyzar!

Posted at 4:37 PM on February 05, 2008

Garmin Software Troubles

Posted at 3:26 AM on February 04, 2008

I decided to rescue a bunch of old data off my old Garmin Forerunner 201 tonight. The only problem is that this is now impossible. Even though 1.5 years worth of GPS data is on the watch, it’s quite inaccessible now. Google Earth can only read the last 11 routes from the watch. I tried deleting those routes from the 201 and then syncing the watch with Google Earth on my Macbook Pro via a USB to DB9 converter. Unfortunately, on both operating systems the software errors out with “Loaded %1 Waypoints”.

Next, I gave the newest Garmin Training Center a try. Garmin’s software managed to load all the data off the watch using a serial connection on my Windows XP desktop (the 201 doesn’t work with the Mac OS X-version of Training Center) Unfortunately, the map overlays didn’t load for the 201 routes like they do with the Garmin Forerunner 305 ones. Now, all of my historic Forerunner 201 data is half-usable and silo’d up in the training center software with no hope of exporting it out.

Adding insult to injury, Garmin has deprecated the “Export to XML” feature that existed in their old Training Center software. This effectively locks-out third-party developers because the export data is now only available in proprietary TCX format. It’s unbelievable that Garmin wouldn’t continue to support XML or, at the very least, Google Earth’s KML format. This is even more troubling because Garmin used to enable hackers to do cool stuff with their hardware. By allowing access to the unencrypted GPS data, Garmin enabled quite a bit of tinkering. Programs like USAPhotomaps and several community GPS running sites sprouted up as a result. Back in 2005, I even wrote my own GPS overlay program to map data onto a USGS orthoimage of Austin using the exported XML data from the 201.

Strangely enough, I met three of the developers from Garmin’s Motion Based community web site at SFBeta last week. We talked for a while, and I went all GPS-nerd on them. So, the next day, I tried out Motion Based and uploaded the data off my Forerunner 305. The result is that I was completely nonplussed with their site. The only thing extraordinary about the site is how extraordinary it is. What’s particularly troubling is that since you can only access the GPS route data from Garmin’s watches using proprietary software, this is the only community web site that is gong to work with their devices.

Pandora’s Box

Posted at 2:58 PM on February 01, 2008

Some feverish miscreant has managed to upload all six episodes of Adam Curtis’ Pandora’s Box documentary to the youtube. It has a similar theme to his later Century of the Self, but it’s still worth watching.

Episode 1 - The Engineer’s Plot
Episode 2 - To The Brink of Eternity
Episode 3 - The League of Gentlemen
Episode 4 - Goodbye Mrs Ant
Episode 5 - Black Power
Episode 6 - A Is For Atom

Space Talk From Dimension Eugene

Posted at 8:13 PM on January 29, 2008

Adam Curtis Documentaries on Google Video

Posted at 10:20 PM on January 21, 2008

Adam Curtis’ interpretation of current events viewed through a historical and political lens is a tour de force in explaining the absurdity and cognitive dissonance of our current reality. I recommend watching all of them, twice. Curtis is picking up where the greats like Kenneth Clark and Jacob Bronowski have left off. He is their worthy successor.

The Trap

Google Video: Part 1, Part 2, Part 3a, Part 3b, Part 3c

The Trap consists of three, one-hour programs which explore the concept and definition of freedom, specifically “how a simplistic model of human beings as self-seeking, almost robotic, creatures led to today’s idea of freedom.”

(via wikipedia)

The Mayfair Set

Google Video: Part 1, Part 2, Part 3, Part 4

The Mayfair Set looked at how buccaneer capitalists of hot money were allowed to shape the climate of the Thatcher years, focusing on the rise of Colonel David Stirling, Jim Slater, James Goldsmith, and Tiny Rowland, all members of The Clermont club in the 1960s. It received the BAFTA Award for Best Factual Series or Strand in 2000.

(via wikipedia)

The Power of Nightmares

Google Video: Part 1, Part 2, Part 3

The Power of Nightmares, subtitled The Rise of the Politics of Fear, is a BBC documentary film series, written and produced by Adam Curtis. The series consists of three one-hour films, consisting mostly of a montage of archive footage with Curtis’s narration, which were first broadcast in the United Kingdom in late 2004 and have been subsequently aired in multiple countries and shown in several film festivals, including the 2005 Cannes Film Festival

(via wikipedia)

Century of the Self

Google Video: Part 1, Part 2,Part 3, Part 4

This series is about how those in power have used Freud’s theories to try and control the dangerous crowd in an age of mass democracy.

(Adam Curtis via wikipedia)