Class: Mobility::Plugins::LocaleAccessors

Inherits:
Module
  • Object
show all
Defined in:
lib/mobility/plugins/locale_accessors.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, Mobility.available_locales (i.e. I18n.available_locales, or Rails-set available locales for a Rails application) will be used by default.

Examples:

class Post
  def title
    "title in #{Mobility.locale}"
  end
  include Mobility::Plugins::LocaleAccessors.new("title", locales: [:en, :fr])
end

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*attribute_names, locales:) ⇒ LocaleAccessors

Returns a new instance of LocaleAccessors.

Parameters:

  • One (String)

    or more attribute names

  • Locales (Array<Symbol>)

45
46
47
48
49
50
51
52
# File 'lib/mobility/plugins/locale_accessors.rb', line 45

def initialize(*attribute_names, locales:)
  attribute_names.each do |name|
    locales.each do |locale|
      define_reader(name, locale)
      define_writer(name, locale)
    end
  end
end

Class Method Details

.apply(attributes, option) ⇒ Object

Apply locale accessors plugin to attributes.

Parameters:


36
37
38
39
40
41
# File 'lib/mobility/plugins/locale_accessors.rb', line 36

def self.apply(attributes, option)
  if accessor_locales = option
    accessor_locales = Mobility.config.default_accessor_locales if accessor_locales == true
    attributes.model_class.include new(*attributes.names, locales: accessor_locales)
  end
end