DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Rails - Easily Work With Uppercase Column Names

05.15.2006
| 17257 views |
  • submit to reddit
        I had to work with a legacy database with hundreds of tables with uppercase column names. Here is how I made my life a whole lot easier...

module ActiveRecord
  class MyCustomARClass < ActiveRecord::Base
  
    def self.reloadable?
      false
    end
    
    # all columns are uppercase
    set_primary_key 'ID'
    
    # convert to uppercase attribute if in existence
    # record.name => record.NAME
    # record.id => record.ID
    def method_missing(method_id, *args, &block)
      method_id = method_id.to_s.upcase if @attributes.include? method_id.to_s.upcase.gsub(/=/, '')
      super(method_id, *args, &block)
    end

    # strip leading and trailing spaces from attribute string values
    def read_attribute(attr_name)
      value = super(attr_name)
      value.is_a?(String) ? value.strip : value
    end

    class << self # Class methods
      
      private
        # allow for find_by and such to work with uppercase attributes
        # find_by_name => find_by_NAME
        # find_by_dob_and_height => find_by_DOB_and_HEIGHT
        def extract_attribute_names_from_match(match)
          match.captures.last.split('_and_').map { |name| name.upcase }
        end
    end
  end
end

This was defined in a plugin. Then, in each of my models I used the subclass instead of ActiveRecord::Base, like so...

class MyModel < ActiveRecord::MyCustomARClass
  # ...
end