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, included

Methods included from Mobility::Backend::OrmDelegator

#for

Methods included from Mobility::Backends::ActiveRecord

included

Class Method Details

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


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(::Mobility::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.


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.


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