[Rails] abstract_naming_convention (proposal for new class)

Adelle Hartley adelle at bullet.net.au
Wed Jan 26 05:07:57 GMT 2005


I started writing this before I discovered that I can do this:

ActiveRecord::Base::pluralize_table_names = false

That fixes my immediate problem, but nevertheless...

I propose a new class, that I will call abstract_naming_convention.

Subclasses of this class would implement a conversion between "human" names
and "code" names based on a specific naming convention.

ActiveRecord would need to know about this class, but its potential uses
extend beyond ActiveRecord:

class abstract_naming_convention
	# take a "human" name and return a "code" name.
	def encode(human_name) end
	# take a "code" name and return a "human" name.
	def decode(code_name) end
end

A typical "real life" database makes use of multiple naming conventions.
eg, the naming of tables, the naming of fields, the naming of indexes, etc.

So, ActiveRecord::Base could have a class attribute for each naming
convention used.

Those of us from the "if it ain't broke, don't fix it" school of thought may
need a little convincing, since ActiveRecord::Base already has the following
naming convention related class attributes:

	primary_key_prefix_type
	table_name_prefix
	table_name_suffix
	pluralize_table_names

And it wouldn't be too hard to add a table_name_infix, to indicate whether a
table_name should contain an underscore character between words, etc.

But abstracting the idea of a naming convention out of Active record opens
up some possibilities.

Dealing with exceptions would become a breeze - just subclass a standard
naming convention:

class special_naming_convention < plural_naming_convention
	def encode(human_name)
		# deal with an exceptional case
		if human_name == 'person'
			'people'
		else
			super
		end
	end

	def decode(code_name)
		# deal with an exceptional case
		if code_name == 'people'
			'person'
		else
			super
		end
	end
end


Completely arbitrary table names would also be possible, by creating a
naming_convention that looked up the class name in a table to determine the
table name.  (I have a project where that would be useful, because the
"human" names are too long to represent directly as table names in the
underlying database).

Does anyone here, who has a better knowledge of the standard libraries, know
whether there is already an existing standard class that implements this
pattern?

Adelle.




More information about the Rails mailing list