public
Created

Some handy I18nization for my ApplicationDecorator

  • Download Gist
application_decorator.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
class ApplicationDecorator < Draper::Base
 
# By default, humanize the attributes listed.
#
# Example:
#
# # user_decorator.rb
# class UserDecorator < ApplicationDecorator
# decorates :user
# humanizes :activation_status, :plan_status
# end
#
# See +ApplicationDecorator#humanize+ for a more detailed example.
def self.humanizes(*attrs)
attrs.each do |attr|
define_method attr do
humanize attr
end
end
end
 
# Humanize an attribute using I18n, falling back to the humanized attributes value.
#
# Example:
#
# # user_decorator.rb
# class UserDecorator < ApplicationDecorator
# decorates :user
#
# def activation_status
# humanize :activation_status
# end
#
# def plan_status
# humanize :plan_status
# end
# end
#
# # en.yml
# en:
# active: Current
# user:
# activation_status:
# active: 'Activated'
#
# # Examples:
# @user.activation_status = 'active';
# @user.decorator.activation_status # => 'Activated'
#
# @user.plan_status = 'active'
# @user.decorator.plan_status # => 'Current'
#
# @user.activation_status = 'inactive'
# @user.decorator.activation_status = 'Inactive'
def humanize(attribute, key = model.send(attribute), default = key.to_s.humanize)
i18n_with_scoped_defaults key, [self.class.model_name.i18n_key, attribute], default
end
 
# Try to translate a key with I18n and a scope but fallback to less-and-less scope.
# An example will explain more clearly:
#
# i18n_with_scoped_defaults(:some_key, [:foo, :bar, :baz])
#
# Will try the following I18n translations in order:
# * foo.bar.baz.some_key
# * foo.bar.some_key
# * foo.some_key
# * some_key
#
# And if none of the I18n keys translate, it will use the default param (which defaults to
# humanizing the provided key).
#
def i18n_with_scoped_defaults(key, scope = [], default = key.to_s.humanize)
scope << key
key = scope.join('.').to_sym
 
defaults = []
defaults << scope.join('.').to_sym while scope.delete_at(-2)
defaults << default
 
I18n.t key, default: defaults
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.