Is there an elegant way to map column names

I have been searching high and low but I can’t find an elegant way to
map database column names to model names.

The idea is simple if I have a column named ‘CUSTOM_5’ I want this to
show up as "favorite_pet’.

So far all the suggestions I have seen are to create your custom
methods which is fine but a lot of work if you have to map most if not
all your fields.

Also creating getters and setters means you now have to add those
methods to the to_xml and to_json methods as well as excluding the
original field names.

Surely there is an easier way to handle this very common problem.

Could ruby’s ‘alias’ command work for this? Something like:

alias favorite_pet custom_5
alias favorite_pet= custom_5=

Not sure where you’d put those lines though…

That’s not gonna work because those methods don’t really exist. You
could probably extend AR::Base’s method_missing method, but really,
you should change the database columns’ names.

This should work.

Usage:

class GreenPastures < ActiveRecord::Base

alias_column “new_name” => “old_nAmE”

end

Include this code in a file in /lib

module Legacy
def self.append_features(base)
super
base.extend(ClassMethods)
end
module ClassMethods
def alias_column(options)
options.each do |new_name, old_name|
self.send(:define_method, new_name) { self.send(old_name) }
self.send(:define_method, “#{new_name}=”) { |value|
self.send("#{old_name}=", value) }
end
end
end
end

ActiveRecord::Base.class_eval do
include Legacy
end

class GreenPastures < ActiveRecord::Base

alias_column “new_name” => “old_nAmE”

end

I saw this during my search. I am wondering how this is different that
simply using the ruby alias command.

Of course this won’t effect the “to_xml” and “to_json” methods. They
seem to ignore the local attr.

I guess you’d have to build a hash, call this method for every member
of the hash and finally pass those to the to_xml method.