Class: Mobility::Backends::ActiveRecord::Column

Inherits:
Object
  • Object
show all
Includes:
Mobility::Backends::ActiveRecord, Column
Defined in:
lib/mobility/backends/active_record/column.rb

Overview

Implements the Column backend for ActiveRecord models.

You can use the mobility:translations generator to create a migration adding translatable columns to the model table with:

rails generate mobility:translations post title:string

The generated migration will add columns title_<locale> for every locale in Mobility.available_locales (i.e. I18n.available_locales). (The generator can be run again to add new attributes or locales.)

Examples:

class Post < ActiveRecord::Base
  extend Mobility
  translates :title, backend: :column
end

Mobility.locale = :en
post = Post.create(title: "foo")
post.title
#=> "foo"
post.title_en
#=> "foo"

Backend Accessors collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Column

#column, column_name_for

Methods included from Mobility::Backends::ActiveRecord

included

Class Method Details

.build_node(attr, locale) ⇒ Arel::Attributes::Attribute

Returns Arel node for translation column on model table.

Parameters:

  • attr (String)

    Attribute name

  • locale (Symbol)

    Locale

Returns:

  • (Arel::Attributes::Attribute)

    Arel node for translation column on model table



58
59
60
61
# File 'lib/mobility/backends/active_record/column.rb', line 58

def self.build_node(attr, locale)
  model_class.arel_table[Column.column_name_for(attr, locale)]
    .extend(Plugins::Arel::MobilityExpressions)
end

Instance Method Details

#each_locale {|Locale| ... } ⇒ Object

Yields locales available for this attribute.

Yield Parameters:

  • Locale (Symbol)


50
51
52
# File 'lib/mobility/backends/active_record/column.rb', line 50

def each_locale
  available_locales.each { |l| yield(l) if present?(l) }
end

#read(locale, _ = {}) ⇒ Object

Gets the translated value for provided locale from configured backend.

Parameters:

  • locale (Symbol)

    Locale to read

Returns:

  • (Object)

    Value of translation



39
40
41
# File 'lib/mobility/backends/active_record/column.rb', line 39

def read(locale, _ = {})
  model.read_attribute(column(locale))
end

#write(locale, value, _ = {}) ⇒ Object

Updates translation for provided locale without calling backend’s methods to persist the changes.

Parameters:

  • locale (Symbol)

    Locale to write

  • value (Object)

    Value to write

Returns:

  • (Object)

    Updated value



44
45
46
# File 'lib/mobility/backends/active_record/column.rb', line 44

def write(locale, value, _ = {})
  model.send(:write_attribute, column(locale), value)
end