Playing Nice with Legacy Data

I was working with a database that had its own rules for pluralization and I wrote a quick hack to try to get ActiveRecord to play nice with their naming conventions. It still crashes and burns a lot, but it’s a work in progress.

module Inflector
  def pluralize(word)
    if (  word[-1..-1].downcase == 's' ||
          word[-1..-2].downcase == 'sh' ||
          word[-1..-2].downcase == 'ch' ||
          word[-1..-1].downcase == 'x'        
       )
      word << 'es'
    elsif word[-1..-1].downcase == 'y'
      if ['a', 'e', 'i', 'o', 'u'].include? word[-2..-2]
        word << 's'
      else
        word = word[0..word.length-2] << 'ies'
      end
    else
      word << 's'
    end
  end

  def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
    class_name
  end
end

class ActiveRecord::Base
  class << self
    def reset_primary_key #:nodoc:
      key = "#{base_class.name}ID"
      set_primary_key(key)
      key
    end

    private
    def undecorated_table_name(class_name = base_class.name)
      table_name = Inflector.pluralize(class_name)
      puts table_name
      table_name
    end
  end
end

It still needs a lot of work, but I think it will be pretty cool to get active record to make correct assumptions about table names and keys without explicitly defining them.

Posted by Scott Wed, 13 Feb 2008 23:54:00 GMT