Class: Globalize::ActiveRecord::Adapter

Inherits:
Object
  • Object
show all
Includes:
AdapterDirty
Defined in:
lib/globalize/active_record/adapter.rb

Instance Attribute Summary collapse

Attributes included from AdapterDirty

#dirty

Instance Method Summary collapse

Methods included from AdapterDirty

#_reset_attribute, #changed, #changed_attributes, #changes, #clear_dirty, #store_old_value, #write

Constructor Details

#initialize(record) ⇒ Adapter

Returns a new instance of Adapter.



11
12
13
14
# File 'lib/globalize/active_record/adapter.rb', line 11

def initialize(record)
  @record = record
  @stash = Attributes.new
end

Instance Attribute Details

#recordObject

The cache caches attributes that already were looked up for read access. The stash keeps track of new or changed values that need to be saved.



6
7
8
# File 'lib/globalize/active_record/adapter.rb', line 6

def record
  @record
end

#stashObject

The cache caches attributes that already were looked up for read access. The stash keeps track of new or changed values that need to be saved.



6
7
8
# File 'lib/globalize/active_record/adapter.rb', line 6

def stash
  @stash
end

Instance Method Details

#fetch(locale, name) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/globalize/active_record/adapter.rb', line 23

def fetch(locale, name)
  record.globalize_fallbacks(locale).each do |fallback|
    value = stash.contains?(fallback, name) ? fetch_stash(fallback, name) : fetch_attribute(fallback, name)

    unless fallbacks_for?(value)
      (value, :locale => fallback, :requested_locale => locale)
      return value
    end
  end

  return nil
end

#fetch_stash(locale, name) ⇒ Object



16
17
18
# File 'lib/globalize/active_record/adapter.rb', line 16

def fetch_stash(locale, name)
  stash.read(locale, name)
end

#resetObject



54
55
56
# File 'lib/globalize/active_record/adapter.rb', line 54

def reset
  stash.clear
end

#save_translations!Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/globalize/active_record/adapter.rb', line 36

def save_translations!
  stash.each do |locale, attrs|
    next if attrs.empty?

    translation = record.translations_by_locale[locale] ||
                  record.translations.build(locale: locale.to_s)
    attrs.each do |name, value|
      value = value.val if value.is_a?(Arel::Nodes::Casted)
      translation[name] = value
    end

    ensure_foreign_key_for(translation)
    translation.save!
  end

  reset
end