avatarharuki zaemon

Alias a Static Method in Ruby

By

As much as I love Ruby on Rails, one of the things that dissapoints me is the rather large number of static methods. Maybe it’s my Java background but class methods just irk me: They’re difficult to override, mock, stub-out, and they’re inherintly thread-unfriendly. But that aside, the fact remains that they exist and, now and again, I need to mess with them. Case in point: My Foreign Key Migrations plugin.

The plugin was working fantastically – thanks to the efforts of Ted Davis for giving it a work out – until it came time to running functional tests. Unfortunately, but unsurprisingly, the schema dumper used to copy the database structure from development to test creates tables in alphabetical order. Now I can’t actually think of a much better alternative but the problem is that this means the foreign key clauses were being generated against tables that possibly didn’t exist at the time of execution. (For example, Order sorts before Product however the orders table has a foreign key to the products table.)

So anyway, the longer-term solution is to batch up the foreign-key declarations until the end of the script and then execute them but in the meantime, I just wanted to disable their generation altogether. In either case, I needed to interfere with the execution of ActiveRecord::Schema.define a static (boo, hiss) method. Now, for the fun bit.

In Ruby, the way to safely mix-in methods (rather than use subclassing) is to use some method chaining. For this we use alias_method. So, for example, if we wanted to override to_s to always place quotes around the value (nopt very useful but it will suffice for now) we could write a module like this:

module QuoteToSdef self.included(base)base.class_eval do**alias_method :to_s_without_quotes, :to_s** unless method_defined?(:to_s_without_quotes)**alias_method :to_s, :to_s_with_quotes**endenddef to_s_with_quotes"'#{to_s_without_quotes}'"endend

This essentially says that when the module is included (ie mixed-in) to a class then: add a method named to_s_with_quotes; create an alias of the existing to_s named to_s_without_quotes; make an alias of the new to_s_with_quotes named to_s; and finally, whenever to_s. is executed, call the old to_s method (now named to_s_without_quotes) and surround the results with, you guess it, quotes.

To use this you would either manually include the module in a class or, more along the lines of aspects, force the inclusion with some code like this:

MyClass.send(:include, QuoteToS)

(As a side note, the use of unless method_defined?(:to_s_without_quotes) is to work-around a bug in Ruby 1.8.4 that causes an infinite recursion when using alias_method. I never detected it under Mac OS X but apparently it affects windows machines with monotonous regularity. D’oh!)

So that’s all very well and good but what happens when you need to do the same thing with static methods? The answer is, use class << self and extend. In my case, overriding the behaviour of ActiveRecord::Schema.define looks something like this:

module ForeignKeyMigrations::Schemadef self.included(base)**base.extend(ClassMethods)**base.class_eval do**class << self**alias_method :define_without_fk, :define unless method_defined?(:define_without_fk)alias_method :define, :define_with_fk**end**endend**module ClassMethods**def define_with_fk(info={}, &block)...define_without_fk(info, &block)endend**end**

Here, the use of base.extend causes all the methods defined within the module ClassMethods – an aribitrary name used by convention in most if not all the rails code I’ve ever seen – to be added as static methods on the class. Then, surrounding the alias_method calls within a class << self causes them to be executed in a static context.

Again, to have this code mixed-in to the existing ActiveRecord::Schema class looks like this:

ActiveRecord::Schema.send(:include, ForeignKeyMigrations::Schema)

Phew!

P.S. all the plugins are now available via SVN.

UPDATE: See the comments on how to simplify the code thanks to Ryan Tomayko.

Publishing My Rails Plugins

By

I’ve created a page where I’ve started to publish my rails plugins. I don’t yet have a publicly accessible SVN server but I’m in the process of setting one up so, until I get that completed, I’ve packaged the plugins as downloadable .tar.gz files that you can extract into your vendor/plugins directory. So far I’ve published the foreign-key migrations and cascading stylesheets plugins with more to come. But as today is Norway’s national day (apparently celebrating the signing of the constitution on the 17th May, 1814) and I’m in Olso, I’m off to do some drinking..ahem I mean..celebrating.

Auto-Generate Foreign-Key Constraints in Rails

By

I literally just lobbed into my hotel room in Oslo after 30+ hours in transit. (I left home @ 12:30pm on Monday 15th and arrived here @ 21:30 on Tuesday 16th Melbourne time.) It’s my first time in Scandinavia and so far I’m loving it. The people are friendly (and ahem rather attractive I must say) and I’m hanging out to try some scandinavian beer!

So anyways, after resisting the temptation to turn on my laptop, I finally caved and whipped up a little bit of code to auto-generate foreign-key relationships for migration scripts:

module ActiveRecord
  module ConnectionAdapters
    class ColumnDefinition
      alias nofk_to_sql :to_sql

      def to_sql
        name.to_s =~ /(.*)_id$/ ? "#{nofk_to_sql} REFERENCES #{Migrator.proper_table_name($1)} (id)" : nofk_to_sql
      end
      alias to_s :to_sql
    end
  end
end

The code assumes that if you have a column named customer_id in say an order_s_ table, then you want a foreign key to the id column in the customer_s_ table. That doesn’t handle situations where you have multiple foreign keys to the same table but…meh…I don’t have models that sophisticated yet so bite me :)

Just looking back on it now, it was so trivial to implement that there is more syntactic noise than actual code. Hmmmm.

UPDATE: The plugin is now available in downloadable form and supports a :references option for multiple columns or columns that aren’t named for the table they reference.

Using a Single Development Database For all Rails Applications

By

I used to have a separate database and/or user for each application I was developing. This worked for a while but once I had three or so projects underway, I grew tired of remembering which database and which login to use when running psql, etc. In addition, if anyone else wanted to do development, they too needed to either configure another rails environment (eg. james_development) or they had to create another database/user just as I had.

Then it occurred to me that psql (at least under Mac OSX) defaults to connecting to a database named for the currently logged in user. So, I reasoned, if all the developers had a default database, then if I could configure rails to connect to that I might be rid of my myriad databases. The problem was: how?

At first I tried not specifying a database in config/database.yml at all. D’oh! No luck. Then I wondered if I could add an ERB-ish macro for the current user (I may even have read that it was possible but I can’t for the life of me recall where):

development:adapter:  postgresqldatabase: **<%= ENV["USER"] %>**username: **<%= ENV["USER"] %>**

I’m not sure at what level this is being handled (rails, yaml, ruby, somewhere in between) but it worked! Now when the application loads in development, the name of the currently logged in user is substituted in for the name of the database.

The only other thing is to always remember to specify a table-name prefix in config/environments/development.rb and all the applications will happily co-exist in the same, default, database:

  config.active_record.table_name_prefix = "cjp_"

I’ve been playing with having all my applications in the one development database for a while now and it seems to be working out ok. On the down-side, it does mean I need to remember the table-name prefix when using psql, in some ways moving the problem rather than removing it, however it doesn’t seem to get in the way especially because psql has table completion for table-names, column-names, indexes, you name it. (That’s right: select * from cjp_[tab] where [tab] = '...';). The other downside of course is if I ever want to blow away the entire database I can’t but then again, that’s what rake migrate VERSION=0 is for.

I’m not sure if I’ll continue in the long-term with this but it sure makes adding a new developer to the team dead-simple and makes my local machine configuration a lot simpler in the meantime. Besides, I needed an excuse to try using table-name prefixes so I could test my migration extensions. Guess what? They didn’t handle it! They do now :)

Bulletproof Web Design

By

You know that feeling when you grok a programming language so that you spend far less time thinking about the how and thus are free to concentrate more on the what? That’s how I feel about Java and it’s how I’m beginning to feel about Ruby and Rails. The same can’t (or I should say couldn’t) however be said for (X)HTML+CSS. Until now.

Having scoured the net, read every web site I could find and even sat in bookstores for hours reading Eric Meyer, I still didn’t feel comfortable doing web page layout and design. I just didn’t get it. I spent so much time trying to work out how I would create a web page that I lost all my creative drive. I new there just had to be a simpler way. Surely (X)HTML+CSS gives me syntactic markup + layout?!

Finally, in a last ditch effort to put myself – and my friends on IM who I wouldn’t stop bitching to – out of misery, I spent a few hours in Borders (you know, the library with coffee) and stumbled upon Bulletproof Web Design by Dan Cederholm.

It’s a pretty easy read and the examples are very easy to follow. The layout of the book makes a big difference too. I love books that I can just open at any page and get a “nugget” then read on if I feel inclined to do so or even skip back a bit to learn a bit more. This is in stark contrast to the excellent but – for me at least – excruciatingly painful Eric Meyer books which are too densely packed and concentrate too much on the what rather than the how.

I’m still no expert (I’ve really just started) but if you too are in need of some very simple yet practical help in getting you started thinking with the right mindset, I can highly recommend it. If however you’re after an HTML+CSS reference manual or an O’Reilly hacks style of book for that matter, then you might like to try something else.

Hej Sweden (and Norway)

By

I’ll be in Oslo from the 16th until the 19th of May then in Arvika from the 19th until the 22nd and finally Stokholm from the 1st of June until the 7th of June, visiting parts unknown in between so if anyone wants to meet up for a beer and Surstromming (NOT!), that’d be cool. I’ll be doing some work-related stuff as well as attending a few Aikido seminars. Any recommendations? Places to visit? Things to see? Hotels, Motels, Hostels to stay at (or avoid)?

Transactional DDL

By

Have you ever been half way through a rails migration script only to have it bomb out with some error or another? You then correct the error and try to re-run it but because some of the statements have already been executed they fail when executed a second time.

Some databases (PostgreSQL for example) allow you to wrap DDL (Data Definition Language, create table, etc.) as well as DML (Data Manipluation Language, insert, etc.) in a transaction! This means that if any part of the script fails, the whole lot is rolled back. Imagine this: you drop a table, script rolls back and the table magically re-appears as if nothing had happened.

In rails migration scripts it’s a simple matter of wrapping the entire up and/or down method with a _Model_.transaction do ... end. (Yet another time I really think the idea of making transactions a part of the model is particularly ridiculous. Transactions are cross-cutting concerns just like logging. Just ask the Aspect weenies, they’ll tell ya.)

Here’s a simple example:

def self.up
  SystemProperty.transaction do
    create_table :system_property do |t|
      t.column :name,         :text,      :null => false
      t.column :value,        :text,      :null => false
      t.column :created_at,   :datetime,  :null => false
      t.column :updated_at,   :datetime,  :null => false
      t.column :lock_version, :integer,   :null => false, :default => 0
    end
    add_index :system_property, [:name], :unique => true
  end
end

Now, I realise that create_table also supports the :force => true option so this is possibly not the best example but at least you can see how to go about making your migration scripts fully transactional, DDL and all.

More Managing Multiple Rails Environments

By

Yesterday I discussed how we made sure our application was talking to the correct database. Today I’m going to show you how we provide some visual feedback to the user indicating in which environment they’re operating.

As mentioned yesterday, we have four different environments, two of which – UAT and production – are available to the end users and as such it’s imperitive that we provide some visible means for discrimination (lest they mistake one for the other and accidentally add test data into production). Besides obvious gating procedures such as different access rights, etc. one of the ways we can help them out is by providing some obvious visual feedback to indicate the current environment. In this scenario, we decided to change the background colour from gold in production to red in UAT.

One approach might have been to hard-code some style information into the head element of the main application.rhtml template. Something along the lines of:

<% if RAILS_ENV == "uat" -%&gt<style type="text/css">body {background-color: red;}</style><% end -%&gt

The problem with this approach is that, well quite frankly, it smells. For a start, we’ve hard-`d the environment and placed style information directly into each web page – something I’m always reluctant to do if I can avoid it. So what other options do we have?

I’m glad you asked. It turns out that we already had a mechanism in place for including various stylesheets depending on which page is being rendered. For a start, we always include application.css on every page. It contains all the global, system-wide styling information. In addition, we also include a stylesheet for each page – if it exists – based on the path to the current action. So for example, if the current action is list in the CustomerController then we check to see if the stylesheet customer/list.css exists and if so, include it in the rendered output. This allows us to easily add specific styling for individual pages if necessary.

The code for the macro that handles this behaviour looks something like:

def stylesheet_link_tag(*sources)if sources.include? :defaultssources = sources.dupsources.delete :defaultssources << 'application' if File.exists?("#{RAILS_ROOT}/public/stylesheets/application.css")page = "#{@controller.controller_name}/#{@controller.action_name}"sources << page if File.exists?("#{RAILS_ROOT}/public/stylesheets/#{page}.css")endsuper *sourcesend

So if you call the stylesheet_link_tag macro with :defaults as one of the arguments, magic happens.

With this in mind, we decided to enhance the default stylesheets list to include #{RAILS_ENV}.css if it exists (with a little DRY re-factoring in the process):

def stylesheet_link_tag(*sources)if sources.include? :defaultssources = sources.dupsources.delete :defaults['application', **RAILS_ENV**, "#{@controller.controller_name}/#{@controller.action_name}"].each do |source|sources << source if File.exists?("#{RAILS_ROOT}/public/stylesheets/#{source}.css")endendsuper *sourcesend

Now we can easily create a uat.css that looks something like:

body {background: #EB5E66;}

And voila! When users log in to production they see the default (gold) background and in UAT they’re immediately hit with a red – technically it’s ‘cherry’ – one. No mistaking which environment they’re in now.

Again, you don’t have to use a background colour nor even use stylesheets for that matter. The main point is that getting configuration management (of which we consider this to be a part) takes some thought but isn’t that hard to get right, especially in Rails.

Managing Multiple Rails Environments

By

I’ve written briefly on build watermarking and environmentally friendly builds before: Some useful techniques to aid support staff in identifying which particular build of your application is causing your end-users – or testers as is often the case – grief.

In the first of these two articles, I mentioned a project we did many years ago where we stored the build number in the database. When the application connected, it checked to that it was running against the correct database version. This was prompted by one of our biggest clients at the time who had several hundred users all running a client-server application (yes it was a loooong time ago) and we needed to ensure they couldn’t accidentally run the wrong version and potentially corrupt the database.

A similar problem has now cropped up with a rails application we’re developing. This time, rather than a specific build, we’re more interested in ensuring that the application is running against the correct database instance. In this scenario, we have four databases: development; test; uat; and production. Not so much a problem for the first two, but it’d be pretty catastrophic if somehow the UAT application were started against the production database!

Our solution is pretty simple and inline with the previous discussion: put something into the database to identifiy the appropriate environment then check for it in the rails application. The implementation (naturally being rails and all) was also quite simple. We already had a generalised SystemProperty class – essentially just a set of key-value pairs supporting hash-like indexing – o we merely created a new instance, :environment, which is then checked via before_filter in the ApplicationController like so:

class ApplicationController < ActionController::Basebefore_filter :check_rails_env...def check_rails_envraise "Incorrect database: '#{SystemProperty[:environment]}' expected: '#{RAILS_ENV}'" \unless SystemProperty[:environment].value == RAILS_ENVendend

Once the code is in place, all you need do is insert a record into the system_properties table with a key of 'environment' and a value of say 'production' (for, you guessed it the production database) and you’re good to go. If the application ever runs against the wrong database, you’ll be greeted with something along the lines of:

Incorrect database: 'production' expected: 'uat'

A slightly riskier alternative to creating the environment record manually is to perform the task in a database migration script:

class CreateEnvironmentSystemProperty < ActiveRecord::Migrationdef self.upSystemProperty.create! :name => "environment", :value => RAILS_ENVenddef self.downSystemProperty[:environment].destroyendend

I can’t say I particularly recommend this approach though unless you are REALLY, REALLY certain of your environment settings – precisely what you probably aren’t if you’re considering the whole idea in the first place – but, nevertheless, maybe, like me, you just want to ensure that no one can screw up in the future, say while you’re on holidays and you’ve left it up to the new guy ;-)

The one place where this approach falls down is with caching. Because we’ve used a before filter, any actions that are cached will be served up directly by the web server, without going through the rails controller. Practically though, I doubt this will be much of an issue, especially in our particular case where what we’re really worried about is back-office staff either entering data into the UAT database when they thought it was production – a bit of a waste of time but not that bad – or worse, testers entering data into a live system.

Ofcourse this isn’t the only problem faced by developers tasked with managing multiple rails environments and I hope to address some more in future posts.

The Days I Turned Pluralisations: Off

By

Oh what a day it was.

You see, the first real Rails project we did, I thought, “well, I’ll give it a try. This guy seems to know what he’s talkign about and even though pluralisation goes against everything I’ve ever learned or studied with repsect to database design, why not?”

One of the major factors in making rails so productive (for me at least) is that it reduces the cognitive dissonance – between my ideas (creativity) and the implementation (ruby/rails). I find when I’m coding in rails that it’s enabling me to quite literally code what I’m thinking as I’m creating, in way that Java never has. (That’s not necessarily the fault of Java per-se, rather my feeble brain.) The pluralisation stuff seems to fly directly in the face of this.

Well suffice to say that on my second real project, I decided to turn it off, and my brain thanked me for it. I simply added the following to config/environment.rb:

Rails::Initializer.run do |config|
  ...
  config.active_record.pluralize_table_names = false
end

No longer did I need to keep remembering that even though the class is called Entity the table is called Entities. No more pissing around with pluralisation rules because, what-do-you-know, the default ones can’t handle the fact that the plural of UnitOfMeasure is unit**S**_of_measure. No more switching contexts everytime I go from SQL to Ruby code. (Yes, I manually dig around in the database using SQL to make sure I haven’t screwed something up. And yes, I also use the rails console.)

And you know what? In neither project has the customer once asked me to show them the database schema – one of the arguments supposedly for using plural table names. No, in fact if I ever wanted to show the customer anything (other than the application itself), I usually scribbled labelled boxes on a whiteboard and even then, I’ve not once had anyone give me a puzzled look or ask “why is that singular?” Strange perhaps but true!

So whilst I admire the audacity and coding athleticisim of DHH for creating the pluralisation code, I’m far more impressed with the work he and the team have done on Rails 1.1. Everything seems so much “better”: ActiveRecord for one; and especially RJS templates as another example. At least they had the foresight (even pre 1.0) to allow pluralisation to be turned off!

Halleloujah!

Real-estate on Rails

By

Our first Ruby on Rails application finally went live…almost. Having never even looked at Ruby, let-alone Rails, before embarking on the project, it’s been a huge learning experience curve but certainly one worth having.

The site is, as you may have guessed it, a Real-Estate web site for Bowral (and surrounds) in New South Wales – I don’t actually know where that is. The original spec was somewhat of a Design-by-Quark-Express™ and although it was excruciantingly precise on look, lacked a little on functionality.

The result is not too bad for a first go – a spike as James keeps re-assuring me. It’s all very Web 2.0ish with its 800x600 borders and AJAX forms, etc. It has scrolling images, dynamic content and layout here and there, server-side emailing and even an RSS feed or two just for fun. Most of it looks great in all major browsers but sometimes we did have to compromise in favour of Internet Explodrer.

Rails really is a lot of fun to work with, most of the time – indeed the hardest part of the application, besides learning RoR, was the HTML+CSS. The bits that work well, work really, really well: views, routing, configuration, database connections, migrations, plugins, etc. The bits that didn’t work so well were the mailer stuff and, sadly, active record.

The mailer stuff smacks of J2EE: layer, upon layer, upon layer. They got some bits right: emails are essential views just like their HTML counterparts. Unfortunately though, the mailer itself (and consequently the email templates) doesn’t have access to all the cool controller/helper functionality meaning you end up doing a lot of redundant stuff in a controller just so you can send URL’s etc. in emails.

And the of course there’s active record which, I must admit, works wonders for the most part. Single-table inheritence sux big fat wobbly things that don’t fit down your gullet and thus nearly choke you to death before you manage to cough them up. In the end we implemented an acts_as_subclass_of plugin that assumes you have two tables sharing a primary key. Silently failing saves on relationships aren’t much fun either. And I have to say that making transaction a part of a record is kinda dumb. The two things have little to do with one another and arbitrarily choosing to use one class over another when updating multiple records seems so un-railsy. Ok so now I’m being petty but it does irk me that they didn’t get absolutely EVERYTHING right ;-)

Caching has it’s issues as well but we worked around most of the limitations for our needs and it’s working a treat. We essentially have pretty close to a fully on-demand website – include images – generated from a PostgreSQL database. As parts of the site are accessed, the results are cached, eventually resulting in an almost entirely static website. This “warming up” process could easily be automated on deployment.

We really only used two third-party plugins: enumerations; and verbose migrations though we tried a few more but didn’t really see the need in the context of this particular application.

Oh yeah, we’re using SwitchTowerCapistrano making deployment a breeze. Except for the fact that, for some reason, lighttpd doesn’t seem to like being re-started from within the script. Not really a problem as the site needs to migrate to Apache 2.0 + FCGI sometime soon anyway to fit in with the customer’s site management tools but annoying.

Database migrations work fairly well as long as you don’t change your model too much. Pretty much anytime you delete a model class, you need to make a copy of it inside your migration script(s) so they can use it if/when you deploy a brand new application. Somewhat annoying to say the least but I don’t have a better solution, save laboriously checking out each successive “version” of the application one at a time and running migrate. Suggestions anyone?

Still on the database front, I also patched some of the PostgreSQL driver code to fix some bugs (I think I reported them) and to add in missing features such as foreign-key constraints, column check constraints and VACUUM. I know everyone loves MySQL and you’re all probably aware that I don’t but, prejudices aside, you have to love a database that allows you to back-up using:

> pg_dump -o -O cjp_production | gzip > cjp_production.gz

Development was done (for the most part) using TextMate+Subversion on our lovely PowerBooks (yes, we’re so December 2005) and deployed to a FreeBSD box which, I have to say has a very nice package management system. (I always liked FreeBSD back in the version 2/3 days and I like it even more now. It certainly feels like a great platform for production environments.) Virtual PC also came in very handy as for running Windoze in order to test the site.

I think I only used rails’ generate script once to see what it would produce – lot’s of noise – after which I chose to hand-cruft my code. I suspect I’m a control-freak at heart ;-).

The real winner for me though is Ruby. It’s just nice. It too has it’s foibles but I really do find I write less verbose (and certainly less syntactic) code. It has already started to change the way I think about code and I like where I’m headed. It’ll be interesting to see how much it screws up my Java code ;-)

All-in all an very pleasant experience. I’m not a huge fan of web apps in general but Rails certainly makes them much more fun and the rise of DHTML for client-side processing definitely makes for far more interesting client-side applications. I could certainly enjoy making a living this way.

So, anyway, if you’ve ever been interested in owning a property with your own 2-acres of truffles, I know just the place ;-)

Aussie, Aussie, Aussie. Oi Oi Oi.

By

If you live in Australia, and Melbourne in particular, it would be hard not to notice that the Commonwealth Games have been underway for a little over a week now. (If you’ve never heard of the Commonwealth Games then you’re probably not from a former British colony. It’s somewhat like the Olympics but without all those pesky countries such as the USA, Russia and China to make us feel inadequate.)

Anyway, living in Melbourne as I do, it’s hard not to be overwhelmed by the media coverage here and the constant whir of helicopters overhead, no doubt protecting us from all those nasty would-be terrorists that somehow think it’s worth attacking a country that is 85% uninhabitable, in constant drought and has nothing much to offer (according to our media) besides sport.

Australia, it seems, fairs pretty well in the ‘Games. At last tally we had close to double the number of medals of the nearest competitor – Hardly surprising considering we’re second only to the US in terms of public dollars spent on sports.

However, all that money seems a little wasted really. Not because I don’t think sports are important for the health of the nation but because if you were to actually sit and watch any of the television coverage, or read anything in the print media, you’d soon start to wonder if there are actually any other nations competing.

I’ve looked long and hard. I’ve watched every television channel and read evey newspaper I could find but try as I might, I get the distinct impression that the only people competing are from Australia. Indeed in some events, I’m not actually sure what the rules are as no one appears to win a gold medal – the whole point I would have thought. For some strange reason, the only apparent competiror in the race (an Australian do less) somehow had to “make do” with a Silver medal or stranger still, receive no medal at all even though they ran a personal best time.

I know for a fact there are other competitors from other nations here in Melbourne (I presume for the purpose of competing) but besides those named as missing – possibly seeking political asylum – I’m yet to actually see any compete or win medals.

Perhaps I need to go and see an actual event live and have a look for myself? Then again, maybe I’ll stay at home instead and let all those fantastic images of Australians doing so well allow me to forget for a moment the fact that we spend more on our sporting elite than we do on health for the average citizen.

Simply Delicious

By

Like just about everyone these days, I have a Delicious account. (For those of you still living in early 2005, it’s a social bookmarking site.) I use it whenever I have a link to something that I want to remember personally and also for links that I would have blogged about but for which I don’t feel a blog is really the appropriate medium.

One feature I love about deli.cio.us (yes that is the correct spelling) is the inbox. If you haven’t looked at it, it’s a great way to keep track of other peoples bookmarks. So, rather than subscribe to individual bookmark feeds, you can instead add each feed to your inbox and then subscibe to your own inbox. This way you get all the feeds in one shot and it also lets others see what bookmarks you are interested in.

So, if you’re remotely interested in checking out things that I’m interested in or things I think you might be interested, it’s easy to subscribe to my own links or even subscribe to my inbox to see links other people have that interest me.

Writing Under a Doppleganger

By

Apparently a little more than just the text of James’ and my book was translated for the GermanDutch market.

So, I couldn’t help myself…apparently you don’t even have to be translated to be given a pseudonym.

eBay Schmeebay

By

So Phil asks me why I haven’t blogged in so long. The quick answer is: I haven’t had anything much to enrage me recently and consequently I haven’t had much if anything to blog about. (It’s amazing what time away from a computer does for ones mental health.)

The I receive this email:

Dear eBay Member: kwikdigital has informed us that they have not yet received your payment for the following item:CANON IR 8500 w/ NetworkPrinter +K3N FINISHER 85PPM - (#7557660205) No action is being taken against your account at this time. However, it is important to remember that when you bid on or buy an item you are agreeing to a contract between you and the seller. If the situation isn't resolved within 7 days of this reminder, you may receive an Unpaid Item strike under eBay's Unpaid Item Policy. If you don't respond by Mar-03-2006 you may receive an Unpaid Item strike. Most Unpaid Item disputes can be resolved through direct communication between the buyer and seller, and we encourage you to work with your trading partner to reach a resolution. Regards, eBay

Only I’m not an eBay member; never have been; don’t seem myself ever becoming one. So I do the “right” thing and forward it to [email protected] and for my efforts I receive another email:

Thank you for writing to the eBay SafeHarbor Team. The address you wrote to ([email protected]) is no longer in service.Please re-send your email to us through the Contact Us page listedbelow. http://pages.ebay.com/help/contact_us/_base/index.htmlUsing this service will help us direct your email to the rightdepartment and quickly respond to your inquiry. Choosing the mostappropriate topic from this page will help us answer your questionfaster. REPORTING SPOOFIf you received this message after attempting to report an email thatappears to have come from eBay but actually directs you to another site,you must forward the message to us again by using the forward functionof your email program. Make certain that [email protected] is in the "to"field. Do not alter the subject line, add text to your message orforward the email as an attachment. We appreciate your assistance in this matter and apologize for anyinconvenience this may have caused you.Sincerely, eBay SafeHarbor TeamTips to Avoid Spoof:To help our members better protect themselves from spoof Web sites, wehave developed a new feature for the eBay Toolbar called "AccountGuard." Account Guard includes an indicator of when you are on an eBayor PayPal Website, buttons to report fake eBay Websites, and a passwordnotification feature that warns you when you may be entering your eBaypassword into an unverified site. To learn more about the eBay Toolbarwith Account Guard, open a new browser and typewww.ebay.com/ebay_toolbar into the address bar. Note that eBay willnever send you an email that includes a download as an attachment or alink that goes to a page with a download.eBay also recommends that you ensure that your Web browser, operatingsystem, and virus protection software are up to date. Check for updatesat the "Windows Update" link on www.microsoft.com and scan your computerfor viruses often.

Which is all very well and good but I’M NOT AN EBAY MEMBER.

So I follow the link provided to “report spoof” only to be confonted by a series of questions which I dutifully answer and eventually end up on a page telling me how, as an eBay member, I can:

  • Know that an email is really from eBay
  • Tell if Email and websites are impersonating eBay; or
  • An overview of what to do if I suspect account theft

Which would be realy helpful except I wouldn’t have bothered to come here if I didn’t already suspect some kind of fraud because, well geee, I’M NOT AN EBAY MEMBER.

Scouring the page a littlke I found, among all these options, an “Email Us” link which of course I cheerfully click on only to be confronted by a screen asking me to Sign-In which as you know by now is not possible because: I’M NOT AN EBAY MEMBER!

However, being the kind souls that they are, there is also another button marked “Register, it’s fast and free.”

So it would seem that to contact eBay in order to inform them that their system is being used to send unsolicted email to someone who IS NOT AN EBAY MEMBER requires me to become an eBay member. Hmmmm.

Thankfully, it’s even easier and “free’r” to configure my email software to block anything coming from eBay.

CSS: Debugging Position and Size of Elements

By

I’ve been getting into a lot of CSS stuff over the last couple of days and I’m really digging it; it’s so much easier to lay stuff out than with tables! (OK I’m a little slow but I’ve never been much of an HTML man myself.)

One of the most helpful things I’ve learned (thanks to my mate Stuart) is that when trying to layout, position and size an element, it helps to set the background colour to something really obvious and in contrast to the rest of the page (in my case I used bright orange). This way you can see exactly where the borders and margins are.

Thanks Stu!

The Joy of Mighty Mouse

By

My tolerance for things (anything) that don’t work the way I expect them to is about as low as you could possibly imagine. Just ask my work colleagues about how painful it is to work with me when I have to use Eclipse. (And before the flame wars start, it’s not a bad product it just doesn’t work the same way I do. In fact after my last blog entry, Jon described Eclipse as well and truly “Opinionated Software”. I couldn’t agree more.)

So anyway, it came to pass that on Friday 23rd of December, 2005 my laptop died. Yes, my beloved PowerBook just wouldn’t start up. (Of course those same colleagues that deride me for my whining about Eclipse also took great pride in cajoling me over my woosey “laptop”.) Unfortunately it had apparently suffered one too many falls – about half-a-dozen to be precise – as I made my way around the globe earlier in the year.

Distressed as I was I naturally raced off to the Mac store to hand over the carcass and purchase a new, emergency, computer. Knowing full well that the MacIntel laptops were just around the corner – and being prepared to wait for one– I decided to buy an iMac instead. (Yes, yes. It was a G5 which as of three, count ’em, three days ago has become obsolete.)

As I was wandering around the store waiting for my machine to have 2GB RAM installed, my brother – oh yes, he was with me for moral support :) – started playing with a Mighty Mouse; just like the one included with my new iMac and the same ones that nobody (including me) liked. (I had twice attempted to use one and twice failed. James even offered me his for nix as he disliked it so much!) “Hey! This is pretty cool!” my brother yells across the shop floor. “You have to be kidding me!? Those things suck ass! I just can’t seem to get the right-click thing to work!” I replied.

It was true. I had just never been able to get the right-click to work. It was a shame really because I really like the tactile sense of the track-ball thingy; it’s almost erotic..ok, forget I said that. Anyway, after explaining my issues and demonstrating my complete inability to operate the Mighty Mouse my brother emphatically exclaims “You’re a retard! How can you find it so difficult to use? The only explanation is you’re a retard!” Nice. So after some investigation in the shop and after providing much entertainment to the staff as a matter of consequence, he (my brother) deduces the problem: “You’re resting your hand on it and gripping” hey says. “Of course I am. How else does one use a mouse?” I enquired. “My arm and hand will get tired if I don’t!” I refused to believe that this mouse was any good at all. What a piece of crap. I wouldn’t be budged until he said something that really hit a chord: “Think about how pianists hold their hands. They don’t rest there entire hand on the keys, just their finger tips and they don’t get tired arms.” And what do you know? It worked.

The moment I stopped gripping the mouse and instead lightly holding it with my fingertips, the moment I was able to right-click just fine. What’s even more impressive is that at the end of a day in front of the computer, my hand no longer feels fatigued from using the mouse all day. Who would have thought? I wonder if the mouse was design in this way purposefully or whether it was sheer luck? Whatever the reason, I now love my Mighty Mouse and what’s more, I actually miss it!

Databases: A Necessary Evil?

By

It’s an attitude that I see all too often in developers, especially those that label themselves Object-Oriented Purists who are supposedly capable of precise, rational thought, above and beyond that which we might expect from your mere mortal developer.

Ever since my little rant on the subject over a year ago now I have been tempted time and time again to write something more but each time I go to put finger to keyboard I’m overwhelmed with a sense of resignation to the fact that when it comes to relational databases, most people just don’t get it. If I only had a dollar for every time a developer has adamantly told me that foreign keys are a waste of time and that somehow primary keys are a neccessary evil to satisfy the requirements imposed by the database so that we can look up a record. “Why would I need all that nonsense?” they chortle rhetorically, “my application handles all that stuff just fine.” Sure it does, so prove it!

What I find even more frustrating is the FUD spread by those I expect to know better. Case in point. I was doing some reading of old Ruby On Rails – yes, my shiny, not so new, toy – newsgroup postings when I came upon this from none other than Mr. Rails himself:

And let it be no secret that I consider the database a necessary evil for the object-oriented domain model. Not the other way around. Hence, when given the choice between implementations that pit OO model against database purity, I will almost always side with the OO model. – David Heinemeier Hansson

Now the statement just quoted was apparently a justification for Single Table Ineritence and the absence of Mutliple Table Inheritence in rails. Fine. I have no issue with this at all. In fact one of the things I like about Rails is the fact that it is unashamedly “Opinionated Software”: stuff works the way it does in Rails because, well, because that’s the way someone decided it should. So why shy away from this with some spurious argument about what is/isn’t good database design? Why not just admit that it’s a personal preference and indeed that’s the real reason it’s like that? Would you consider Active Record a necessary evil or simply a design choice? I guess it depends who made the choice ;-)

So anyway, let’s clear a few things up. Firstly, I’m fairly sure that when he (DHH) says database what he actually means to say is relational database – surely he doesn’t mean Object-Oriented Database? Secondly, even though he means to say relational database, what he actually should be saying is SQL database – believe it or not there’s a BIG difference!

Admittedly C. J. Date is not the most exciting read for many people but if you take the time to read some of his work on Relational Database theory, you might be compelled to re-consider your notion of the so-called “impedence mismatch” between Object-Oriented Design and Relational Databases:

… As far as I’m concerned, an object/relational system done right would simply be a relational system done right, nothing more and nothing less. – C. J. Date

I found it fascinating when I spent some time at a university many years ago that database theory was the least popular subject. Maybe it’s just me? Maybe I really enjoy the subject because I see elegance and simplicity and yet enormous power in Relational Databases and it Just Made Sense™.

Relatonal Databases surely aren’t as sexy as Ruby or Rails but neither are they glorified record management systems. They are very precise and provably correct repositories for our data. So, do what you will with databases, treat them as evil if you wish. but I think it behooves us to try and understand what we actually think we’ve supposedly moved beyond.

Update 18 January 2006

Primary Keyvil, Part I

Subversion Gotcha #17

By

Ok, so actually it’s the first that has bitten me but calling it #1 implies it’s the worst one there is and who am I to bestow that honour ;-)

I refer you to this positing in an SVN news group.

It seems that by default, when using Berkely DB with SVN, the default setting is to auto remove log files. Now log files serve a purpose: they allow you to re-play transactions. If those log files no longer exists…no guesses needed.

The rationale for the decision to have this behaviour by default (and I’m paraphrasing): We (the SVN community) don’t want people to complain to us with silly stuff like my disk is full. Rather we’d prefer that in the unlikely event of a repository crash, we’d rather that poor sod looses his days work. We made a trade-off between convenience and security.

Hmmm…let me think about that. How often does my hard disk crash? Almost never. And how often do I need to restore from a previous version of a file? Almost never. And how often do I back up my hard disc? Every day. Gee…maybe I don’t need a versioning repository?

If I said that at work, I’d be laughed off the premisis. Why? Because a repository is more than just a network filesystem. Moreover, it holds one of my companies major assets: the source-code.

I think I can live with my disk filling temporarily every once in a while versus losing a days work multiplied by 50 developers. In the worst case no one can check in. At least we know there’s a problem.

So anyway, this bit me last night when the server on which my SVN repository resides had an NFS failure and corrupted some files. No problem, we can just replay the log…oh they’re not there!

One could argue that I (as the maintainer of the repository) should have known about this option and turned it off. However that argument simply doesn’t wash as the main argument for turning it on by default in the first place was that most people coming over to SVN won’t know enough about how to configure SVN to do the right thing so a choice was made in favour of convenience.

Thankfully, we have daily backups and (in this instance) we only lost two commit sets. So what am I whining about? I’m whining in the hope that this doesn’t happen to you under more critical circumstances.

So how about turning that option off by default and putting a big notice in big bold red lettering on the front cover saying “If your disk fills up, it’s most likely the logs. Go delete the log files for any days for which you have backups. Leave the ones for which you presently have no backups – ie todays.” Not so hard now is it?

How To Write eql?() in Ruby

By

So, as I’ve been delving into Ruby more and more of late and I needed to write an eql?() method for one of my classes. (eql?() is the Ruby equivalent of equals() in Java.)

Understanding how to write an equals() method in Java is one of the most fundamental yet poorly understood practices (if you’re not worried about equals() or hashCode() then I suggest you never use a HashMap) and I wondered if the same was true of Ruby.

The most common mistake looks like this:

public boolean equals(Object object) {
  if (this == object) {
    return true;
  } else if (**!(object instanceof MyClass)**) {
    return false;
  }

  MyClass other = (MyClass) object;
  return this.x == other.x && this.y == other.y;
}

Spot the mistake? It’s subtle yet very VERY wrong. Thankfully – now that we’ve largely managed to get over our obsession with deep inheritence hierarchies – it’s effects aren’t felt that often. The problem is that equals() needs to be symmetric: a.equals(b) should return the same result as b.equals(a).

Now, imagine a class Person with attributes of name and address and another class Employee extends Person with an extra attribute of company. Given the previous implementation of equals, what do you think the chances that the following two statements will return the same result?

person.equals(employee);
employee.equals(person);

So anyway, unlikely or not, it’s still no excuse not to be precise so, in Java the canonical form of an equals() method should look roughly – give or take some formatting and style – like:

public boolean equals(Object object) {
  if (this == object) {
    return true;
  } else if (object == null || **getClass() != object.getClass()**) {
    return false;
  }

  MyClass other = (MyClass) object;
  return this.x == other.x && this.y == other.y;
}

Now we’re comparing based on the actual class and as such the implementation is symmetric; no more problems.

Assuming I still know next to nothing about Ruby, I decided I wouldn’t let my Java habits get in the way of learning something new so I searched the ’net for some examples of how to implement eql>().

After failing dismally to find anything non-trivial, I realised that Rails probably had something in ActiveRecord::Base and I was rewarded with:

def eql?(object)
  self == (object)
end
def ==(object)
  object.equal?(self) ||
  ( object.instance_of?(self.class) &&
    object.id == id &&
    !object.new_record? )
end

Nothing too outrageous: eql?() simply delegates to == (nice syntactic sugar); and == does pretty much the same thing as we would have done in Java only a little more terse. (object.instance_of?(self.class) is Ruby’s way of saying getClass() == object.getClass(); the Ruby equivalent of Java’s instanceof is kind_of?().) We could easily re-write this – although I wouldn’t in practice – as:

def ==(object)
  if object.equal?(self)
   return true
  elsif !object.instance_of?(self.class)
   return false
  end

  return object.id == id && !object.new_record?
end

So it seems – I trust the Rails guys to get this stuff right– that the same rules apply in Ruby as in Java. (I had no real reason to suspect otherwise but hey, it s nice to have it confirmed.)

Now if only someone could explain to me why Hash#reject() and Hash#select() aren’t symmetric: one returns a Hash; the other an Array.

Update 2009-11-02

Almost 4 years later I stumbled on this post and to my horror noticed that my naivety with Ruby at the time allowed me to believe the Rails code when really I shouldn’t have. Here’s the way the eql? method should have been written in the first place:

def eql?(object)
  if object.equal?(self)
   return true
  elsif !self.class.equal?(object.class)
   return false
  end

  return object.id == id && !object.new_record?
end

Or, if you don’t care about the optimisation:

def eql?(object)
  self.class.equal?(object.class) &&
    object.id == id &&
    !object.new_record?
end