Skip to content

Instantly share code, notes, and snippets.

@kjlape
Last active June 7, 2017 22:19
Show Gist options
  • Select an option

  • Save kjlape/377aac73ce69e9fd22e51f9c909864d0 to your computer and use it in GitHub Desktop.

Select an option

Save kjlape/377aac73ce69e9fd22e51f9c909864d0 to your computer and use it in GitHub Desktop.
module I18nHelper
def i18n
ChainableTranslation.new
end
class ChainableTranslation
attr_reader :options
def initialize(scopes = [], options = {})
@scopes = Array(scopes)
@options = options
end
def to_s(options = {})
scope = @scopes.join('.')
I18n.t scope, self.options.deep_merge(options)
end
alias_method :+, :to_s
def +@
to_s
end
def locale=(locale)
to_s locale: locale
end
def [](*scope, scope_or_options)
result = if scope_or_options.respond_to? :to_hash
__chain_i18n_options__ scope_or_options.to_hash
else
__chain_i18n_scope__ scope_or_options
end
result.__chain_i18n_scope__ scope
end
def method_missing(scope)
__chain_i18n_scope__ scope
end
def respond_to?(*)
true
end
def __chain_i18n_scope__(scope)
self.class.new @scopes + Array(scope), self.options
end
def __chain_i18n_options__(options)
self.class.new @scopes, self.options.deep_merge(options)
end
end
end
RSpec.configure do |c|
c.include I18nHelper
end
# Normal use:
i18n.models.chicken.flap.to_s ==
I18n.t('models.chicken.flap')
# I18n params are passed through:
i18n.models.chicken.scratch_a.to_s(object: i18n.objects.dirt) ==
I18n.t('models.chicken.scratch_a', object: i18n.objects.dirt)
# Interpolate easily
farmer = Farmer.first
%w(dog rooster hen).map { |animal| i18n.models[animal].greeting + { subject: farmer.name } } ==
%w(dog rooster hen).map { |animal| I18n.t("models.#{animal}.greeting", subject: farmer.name) }
# Use interpolation to get around edge cases, like nested modules:
+i18n.models['admin/tyson_hq'].district ==
I18n.t('models.admin/tyson_hq.district')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment