Skip to content

Instantly share code, notes, and snippets.

@amiel
Created November 3, 2011 22:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amiel/1338134 to your computer and use it in GitHub Desktop.
Save amiel/1338134 to your computer and use it in GitHub Desktop.
Some handy I18nization for my ApplicationDecorator
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment