Skip to content

Instantly share code, notes, and snippets.

@robhurring
Created January 2, 2013 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robhurring/4436305 to your computer and use it in GitHub Desktop.
Save robhurring/4436305 to your computer and use it in GitHub Desktop.
small concern that allows you to override the field names for validation messages
# small concern that allows you to override the field names for validation messages
#
# Example:
#
# # without concern
# class User < ActiveRecord::Base
# validates :name, presence: true
# end
# # => "Name can't be blank"
#
# # with concern
# class User < ActiveRecord::Base
# include CustomFieldNames
# # use "My name" instead of "Name"
# rename_fields :name => 'My name'
#
# validates :name, presence: true
# end
# # => "My name can't be blank"
#
module CustomFieldNames
extend ActiveSupport::Concern
included do
extend ClassMethods
class_attribute(:_field_name_map){ Hash.new }
end
module ClassMethods
# Example:
# rename_fields :column => 'New Name'
def rename_fields(map = {})
self._field_name_map = map.symbolize_keys
end
# override some error messages to use our custom column names
def human_attribute_name(attribute, options = {})
self._field_name_map[attribute.to_sym] || super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment