Wednesday, December 27
I live and work in Canada. It follows, then, that I often need to generate a select box for Canadian provinces, especially for my work at Unspace. Jealous of the built-in helper for Rails that implements country selection, I whipped up a simple plugin.
All it does is extend ActionView::Helpers::FormOptionsHelper adding the methods province_select, and province_options_for_select.
Get it from subversion via:
svn://visioni.st/p/canadian_provinces
And yes, it includes tests.
Friday, December 22
I recently discovered this little nugget. After reading Jay Fields’ post on the topic of decoupling and the law of Demeter I’ve been using Ruby’s Forwardable module to accomplish basic delegation tasks. Alas, Rails (via ActiveSupport) has a really handy method that encapsulates this pattern quite nicely: a class method called delegate
Consider a Person class with an associated Profile. Pretend the Profile class has an associated collection called favorite_books.
class Person < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :person
has_many :favorite_books
end
If you wanted to see a Person’s favorite books collection, you’d have to go through profile:
Person.find(:first).profile.favorite_books
Which of course would throw a no method error if profile returned Nil. Using delegation, we can do this:
class Person < ActiveRecord::Base
has_one :profile
delegate :favorite_books, :to => :profile
end
Now we can say:
Person.find(:first).favorite_books
and not have to worry whether the profile exists or not, thus alleviating us from having to write an accessor in Person like def favorite_books() profile ? profile.books : nil; end.
Very nice indeed.
Thursday, December 21
Today I realized that I was running Ruby 1.8.4. Actually, I knew I was running 1.8.4, but I’d been ignoring the fact because I’m too lazy to update and I lacked a compelling reason. Well, tonight I decided to bite the bullet and upgrade. It was a painless affair. Unlike Obie’s experience.
Here’s a little script I wrote to automate the process before I started. I generally like to script things ahead of time because doing so is less error prone. You get to think about what you’re doing before you do it. Anyways, YMMV.
#!/bin/sh
PREFIX="/usr/local"
READLINE_VERSION="5.2"
RUBY_VERSION="1.8.5-p2"
curl -O ftp://ftp.gnu.org/gnu/readline/readline-${READLINE_VERSION}.tar.gz
tar xzvf readline-${READLINE_VERSION}.tar.gz
pushd readline-${READLINE_VERSION}
./configure --prefix=${PREFIX}
make
make install
popd
curl -O ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-${RUBY_VERSION}.tar.gz
tar zxvf ruby-${RUBY_VERSION}.tar.gz
pushd ruby-${RUBY_VERSION}
./configure --prefix=${PREFIX} --enable-pthread --with-readline-dir=${PREFIX}
make
make install
popd
Save this to a file named install_ruby.sh and run it from the CLI as follows:
$ sudo sh install_ruby.sh
That should do it.