Created
July 30, 2014 02:45
-
-
Save donaldpiret/f0608202c12092af250b to your computer and use it in GitHub Desktop.
Concern to rename attribute column names for validation errors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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