codahale.com٭blog

Coda Hale lives in Berkeley, CA, where he writes about Ruby on Rails, usability, web design and development, and the occasional bit about bicycles.

Wrapping my head around Ruby (with just a hint of Rails)

I spent much of yesterday’s work day working on a screen-scraping script using Ruby, and wow it’s nice. I kept on finding that I was writing code I didn’t need to; Ruby can compress large, cumbersome structures into clean, readable bits of code. It’s parsimonious, but unlike Perl in that it’s not some inscrutable noise of ampersands and exclamation points.

When I first started learning about Ruby, I thought it was ugly. Way ugly. It didn’t have a sense of closure in its syntax, and it seemed more like the mutant offspring of Python and PHP than anything else. I hear that a lot from others, and it’s an indicator that they haven’t internalized the patterns that Ruby uses.

It’s amazing how much time you can save by using it.

Just make a database module…

I mean, check out this script, using ActiveRecord:

script-db.rb

require 'rubygems'
require_gem 'activerecord'

# establish MySQL connection
ActiveRecord::Base.establish_connection(
	:adapter => 'mysql',
	:host => 'localhost',
	:database => 'rubydata',
	:username => 'rubytest',
	:password => 'rubypassword'
)

# define models for database entries
class Item < ActiveRecord::Base
	belongs_to :owner
end

class Owner < ActiveRecord::Base
	has_many :items
end

…and then use it!

Just do a little require 'script-db' at the top of your script, and you now have the world’s easiest way to save data to your database:

coda = Owner.new
coda.name = 'coda'
coda.save

ruby_clue = Item.new
ruby_clue.name = 'A clue about Ruby'
ruby_clue.value = 3_000_000 # 3 million
ruby_clue.owner = coda
ruby_clue.save

Now how cool is that? I often wondered how well Ruby would work for glue code. Now I know: brilliantly.

Comments are closed.