Module: Translatable::ActiveRecord::InstanceMethods

Defined in:
lib/translatable/active_record/instance_methods.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/translatable/active_record/instance_methods.rb', line 10

def self.included(base)
  # Maintian Rails 3.0.x compatibility ..
  if base.method_defined?(:assign_attributes)
    base.class_eval %{
      def assign_attributes(attributes, options = {})
        with_given_locale(attributes) { super }
      end
    }
  else
    base.class_eval %{
      def attributes=(attributes, *args)
        with_given_locale(attributes) { super }
      end

      def update_attributes!(attributes, *args)
        with_given_locale(attributes) { super }
      end

      def update_attributes(attributes, *args)
        with_given_locale(attributes) { super }
      end
    }
  end
end

Instance Method Details

#end_translateObject



66
67
68
69
# File 'lib/translatable/active_record/instance_methods.rb', line 66

def end_translate
  @translate_me = nil
  self
end

#read_attribute(name, options = {}) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/translatable/active_record/instance_methods.rb', line 88

def read_attribute(name, options = {})
  options = {:translated => true, :locale => Translatable.locale}.merge(options)
  if translated?(name) and options[:translated]
    serialized_value = super(name) if self.serialized_attributes.has_key?(name)
    if translate? && (value = translatable.fetch(options[:locale] || Translatable.locale, name, serialized_value))
      value
    else
      super(name)
    end
  else
    super(name)
  end
end

#reload(options = nil) ⇒ Object



71
72
73
74
75
76
77
# File 'lib/translatable/active_record/instance_methods.rb', line 71

def reload(options = nil)
  @translate_me = false
  translation_caches.clear
  translated_attribute_names.each { |name| @attributes.delete(name.to_s) }
  translatable.reset
  super(options)
end

#saveObject



79
80
81
82
# File 'lib/translatable/active_record/instance_methods.rb', line 79

def save(*)
  @translate_me = false
  super
end

#translatableObject



6
7
8
# File 'lib/translatable/active_record/instance_methods.rb', line 6

def translatable
  @translatable ||= Adapter.new(self)
end

#translateObject



61
62
63
64
# File 'lib/translatable/active_record/instance_methods.rb', line 61

def translate
  @translate_me = true
  self
end

#translate?Boolean

Returns:

  • (Boolean)


84
85
86
# File 'lib/translatable/active_record/instance_methods.rb', line 84

def translate?
  !@translate_me.nil? && @translate_me
end

#translated?(name) ⇒ Boolean

Returns:

  • (Boolean)


102
103
104
# File 'lib/translatable/active_record/instance_methods.rb', line 102

def translated?(name)
  self.class.translated?(name)
end

#translated_attributesObject



106
107
108
109
110
# File 'lib/translatable/active_record/instance_methods.rb', line 106

def translated_attributes
  translated_attribute_names.inject({}) do |attributes, name|
    attributes.merge(name.to_s => translation.send(name))
  end
end

#translation_cachesObject



171
172
173
# File 'lib/translatable/active_record/instance_methods.rb', line 171

def translation_caches
  @translation_caches ||= {}
end

#translation_for(locale, name, build_if_missing = false) ⇒ Object



122
123
124
125
126
127
128
129
130
# File 'lib/translatable/active_record/instance_methods.rb', line 122

def translation_for(locale, name, build_if_missing = false)
  unless translation_caches["#{locale}_#{name}"]
    # Fetch translations from database as those in the translation collection may be incomplete
    _translation = translations.detect{|t| t.locale.to_s == locale.to_s && t.key.to_s == name.to_s }
    _translation ||= translations.build(:locale => locale) if build_if_missing
    translation_caches["#{locale}_#{name}"] = _translation if _translation
  end
  translation_caches["#{locale}_#{name}"]
end

#translation_for_serialized(locale, name, value, build_if_missing = false) ⇒ Object

Fetch translations per keys in the form model_attr_serialized_attribute E.G.1: “‘Model“` has attribute “`config“` which has a key “`auto_save“`

will have a translation key ```config_auto_save```

E.G.2: “‘Model“` has attribute “`config“` which is an array of “`user_id => ([0-9]+)“`

will have translations key containing the index: ```config_user_id_0```, ```config_user_id_1```...


138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/translatable/active_record/instance_methods.rb', line 138

def translation_for_serialized(locale, name, value, build_if_missing = false)

  unless translation_caches["#{locale}_#{name}"]
    engine = self.serialized_attributes.has_key?(name) ? nil : JSON
    deserialized_value = engine.nil? ? value : engine.load(value)

    only = self.translated_serialized_attributes[name.to_sym].map(&:to_s)
    if only.empty?
      regex_keys = /\A#{name.to_s}_([a-z_]+[a-z])(?:_([0-9]*))?\Z/
    else
      regex_keys = /\A#{name.to_s}_(#{only.join('|')})(?:_([0-9]*))?\Z/
    end
    # Fetch translations from database as those in the translation collection may be incomplete
    _translations = translations.select{|t| t.locale.to_s == locale.to_s && t.key.to_s =~ regex_keys }
    _translations.each do |t|
      matched = t.key.match regex_keys
      unless matched.nil?
        if matched.size == 3
          sub_attr = matched[1]
          index = matched[2].to_i
          value[index][sub_attr] = t.value if value.size > index && value[index].has_key?(sub_attr)
        elsif matched.size == 3
          sub_attr = matched[1]
          value[sub_attr] = t.value if value.has_key?(sub_attr)
        end
      end
    end

    translation_caches["#{locale}_#{name}"] = value
  end
  translation_caches["#{locale}_#{name}"]
end

#translations_by_locale(&block) ⇒ Object



192
193
194
195
196
197
# File 'lib/translatable/active_record/instance_methods.rb', line 192

def translations_by_locale(&block)
  translations.each_with_object(HashWithIndifferentAccess.new) do |t, hash|
    hash[t.locale] ||= HashWithIndifferentAccess.new
    hash[t.locale][t.key] = block_given? ? block.call(t) : t
  end
end

#untranslated_attributesObject

This method is basically the method built into Rails but we have to pass => false



114
115
116
117
118
119
120
# File 'lib/translatable/active_record/instance_methods.rb', line 114

def untranslated_attributes
  attrs = {}
  attribute_names.each do |name|
    attrs[name] = read_attribute(name, {:translated => false})
  end
  attrs
end

#with_given_locale(attributes, &block) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/translatable/active_record/instance_methods.rb', line 176

def with_given_locale(attributes, &block)
  attributes.symbolize_keys! if attributes.respond_to?(:symbolize_keys!)

  locale = respond_to?(:locale=) ? attributes.try(:[], :locale) :
      attributes.try(:delete, :locale)

  if locale && !respond_to?(:locale=)
    already = translate?
    translate unless translate?
    Translatable.with_locale(locale, &block)
    end_translate unless already
  else
    yield
  end
end

#write_attribute(name, value, options = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/translatable/active_record/instance_methods.rb', line 36

def write_attribute(name, value, options = {})
  if translated?(name) && translate?
    options = {:locale => Translatable.locale}.merge(options)

    # Dirty tracking, paraphrased from
    # ActiveRecord::AttributeMethods::Dirty#write_attribute.
    name_str = name.to_s
    if attribute_changed?(name_str)
      # If there's already a change, delete it if this undoes the change.
      old = changed_attributes[name_str]
      changed_attributes.delete(name_str) if value == old
    else
      # If there's not a change yet, record it.
      serialized_value = read_attribute(name, options) if self.serialized_attributes.has_key?(name)
      old = translatable.fetch(options[:locale], name, serialized_value)
      old = old.clone if old.duplicable?
      changed_attributes[name_str] = old if value != old
    end

    translatable.write(options[:locale], name, value)
  else
    super(name, value)
  end
end