Last active
June 7, 2017 22:19
-
-
Save kjlape/377aac73ce69e9fd22e51f9c909864d0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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 |
This file contains hidden or 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
| # 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