Skip to content

Instantly share code, notes, and snippets.

@donaldpiret
Created July 30, 2014 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpiret/f0608202c12092af250b to your computer and use it in GitHub Desktop.
Save donaldpiret/f0608202c12092af250b to your computer and use it in GitHub Desktop.
Concern to rename attribute column names for validation errors.
# 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 Concerns
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
self._field_name_map.each do |original, aliased|
self.alias_attribute aliased.to_sym, original.to_sym
end
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
def errors
@errors ||= super
@errors.dup.each do |k, v|
if self.class._field_name_map.keys.include?(k)
@errors.delete(k)
@errors.add(self.class._field_name_map[k], v)
end
end
@errors
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment