Created
October 17, 2015 03:55
-
-
Save AMHOL/6cfe08f650387008b6ab to your computer and use it in GitHub Desktop.
This file contains 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
# gem install i18n | |
require 'i18n' | |
require 'delegate' | |
class ErrorPresenter < SimpleDelegator | |
attr_reader :root_key | |
private :root_key | |
def initialize(root_key, model) | |
@root_key = root_key | |
super(model) | |
end | |
def hash | |
errors.each_with_object({}) do |(attribute, errors), hash| | |
hash[attribute] = errors.map do |error| | |
I18n.t("errors.#{error[:code]}", error[:options]) | |
end | |
end | |
end | |
def messages | |
hash.each_pair.flat_map do |attribute, errors| | |
errors.map do |error| | |
[I18n.t("#{root_key}.attributes.#{attribute}.name"), error].join(' ') | |
end | |
end | |
end | |
private | |
def errors | |
__getobj__ | |
end | |
end | |
I18n.backend.store_translations(:en, { | |
user: { | |
attributes: { | |
username: { | |
name: 'Username' | |
}, | |
password: { | |
name: 'Password' | |
} | |
} | |
}, | |
errors: { | |
length: 'must be between %{min} and %{max} characters long', | |
blank: 'can not be blank' | |
} | |
}) | |
errors = { | |
username: [ | |
{ | |
code: 'length', | |
value: '', | |
options: { | |
min: 1, | |
max: 40 | |
} | |
} | |
], | |
password: [ | |
{ | |
code: 'blank', | |
value: '', | |
options: {} | |
} | |
] | |
} | |
errors = ErrorPresenter.new(:user, errors) | |
errors.hash | |
# => {:username=>["must be between 1 and 40 characters long"], :password=>["can not be blank"]} | |
errors.messages | |
# => ["Username must be between 1 and 40 characters long", "Password can not be blank"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment