Class: I18nAccessors::Methods

Inherits:
Module
  • Object
show all
Defined in:
lib/i18n_accessors/methods.rb

Overview

Defines methods for a set of locales to access translated attributes in those locales directly with a method call, using a suffix including the locale:

article.title_pt_br

If no locales are passed as an option to the initializer, I18n.available_locales will be used by default.

Examples:

class Post
  def title
    "title in #{I18n.locale}"
  end
  include I18nAccessors::Methods.new("title", locales: [:en, :fr])
end

I18n.locale = :en
post = Post.new
post.title
#=> "title in en"
post.title_fr
#=> "title in fr"

Instance Method Summary collapse

Constructor Details

#initialize(*attributes, locales: I18n.available_locales) ⇒ Methods

Returns a new instance of Methods.

Parameters:

  • One (String)

    or more attributes

  • Locales (Array<Symbol>)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/i18n_accessors/methods.rb', line 32

def initialize(*attributes, locales: I18n.available_locales)
  attributes.each do |attribute|
    locales.each do |locale|
      normalized_locale = I18nAccessors.normalize_locale(locale)
      define_method "#{attribute}_#{normalized_locale}" do |*args|
        I18nAccessors.i18n_class.with_locale(locale) { send(attribute, *args) }
      end
      define_method "#{attribute}_#{normalized_locale}?" do |*args|
        I18nAccessors.i18n_class.with_locale(locale) { send("#{attribute}?", *args) }
      end
      define_method "#{attribute}_#{normalized_locale}=" do |value, *args|
        I18nAccessors.i18n_class.with_locale(locale) { send("#{attribute}=", value, *args) }
      end
    end
  end
end