I've been frustrated by the lack of humanity in Rails so-called human names. So I wrote a little library, which was largely stolen from Change displayed column name in Rails validation messages. The library lets you do something a little like this...
require 'human_attributes'
class Puppy < ActiveRecord::Base
humanize_attributes :breakfast => "Puppy's preferred breakfast"
validates_presence_of :breakfast
end
It doesn't do anything very spectacular, but it took me a long time to work out.
# lib/human_attributes.rb
module ActiveRecord
class Base
# Humanize attributes
def self.human_attribute_name(attr)
@humanized_attributes ||= {}
@humanized_attributes[attr.to_sym] || attr.humanize
end
def self.humanize_attributes(*args)
@humanized_attributes = *args
end
end
end
ActiveRecord::Base#human_attribute_name
is deprecated and will be replaced by proper string inflection. For those with fancy, modern humanizing Inflectors you might have to change it to something like this.
def self.humanize_attributes(*args)
humanized_attributes = *args
Inflector.inflections do |inflect|
humanized_attributes.each do |attr, label|
inflect.human attr.to_s, label
end
end
end
Although I couldn't get that to work, probably because my Rails isn't new enough.
[…] Changing human attribute labels in Rails validation messages ä¸ä»‹ç»çš„方法æ¥æœ¬åœ°åŒ– ActiveRecord […]
Rails I18N: ActiveRecord Model Human Name Made Easy @ 知易行难 / 11:36pm / 24 November 2008
Now with Rails 2.2’s I18N, we could do this in a more elegant way. Apps of old Rails version do still need this though. So I bundle your code to a plugin, hosted at github: http://github.com/ashchan/humanize_attributes/tree/master
James Chan / 11:43pm / 24 November 2008
I’m glad you found it useful. I never got elite enough to start writing plugins.
Ryan / 8:23am / 25 November 2008
found useful
test / 6:21pm / 6 February 2012