Error message generation now supports more flexible error format lookup #6249

Closed
wants to merge 2 commits into
from

Projects

None yet

2 participants

@bartvandendriessche

When generating an error message, a format lookup is done for the
following keys:
errors.models.MODEL.attributes.ATTRIBUTE.format
errors.models.SUPERCLASS.attributes.ATTRIBUTE.format (if there's a superclass with I18n support)
errors.attributes.ATTRIBUTE.format
errors.format

If none of these keys are associated with an error format, the default
'%{attribute} %{message}' is used.

@bartvandendriessche bartvandendriessche Error message generation now supports more flexible error format
lookup.

When generating an error message, a format lookup is done for the
following keys:
errors.models.MODEL.attributes.ATTRIBUTE.format
errors.models.SUPERCLASS.attributes.ATTRIBUTE.format (if there's a superclass with I18n support)
errors.attributes.ATTRIBUTE.format
errors.format

If none of these keys are associated with an error format, the default
'%{attribute} %{message}' is used.
c8d2427
@carlosantoniodasilva carlosantoniodasilva commented on an outdated diff May 11, 2012
activemodel/lib/active_model/errors.rb
+ # * <tt>'%{attribute} %{message}'</tt>
+ #
+ def error_formats(attribute)
+ defaults = []
+ if @base.class.respond_to?(:i18n_scope)
+ defaults << :"#{@base.class.i18n_scope}.errors.models.#{@base.class.model_name.i18n_key}.attributes.#{attribute}.format"
+ defaults << :"errors.models.#{@base.class.model_name.i18n_key}.attributes.#{attribute}.format"
+
+ @base.class.lookup_ancestors.map do |klass|
+ defaults << :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.format"
+ defaults << :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.format"
+ defaults << :"errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.format"
+ defaults << :"errors.models.#{klass.model_name.i18n_key}.format"
+ end
+
+ end
@carlosantoniodasilva
Ruby on Rails member

Just my 2 cents: I think there's too much i18n lookups going on here for a simple error formatting, and it would slow down things a bit with the most uncommon usage. Anyway, thanks for your pull request.

@bartvandendriessche

Fair enough.

I found myself needing this bit of functionality in a project, but it's likely to be an uncommon use case, and it does add a bit of a performance hit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment