Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/ext/active_record_ext.rb

Direct Known Subclasses

RailsDbLocalize::Translation

Class Method Summary collapse

Class Method Details

.has_translations(*fields) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ext/active_record_ext.rb', line 4

def has_translations *fields

  unless @__rdbl_translations
    @__rdbl_translations = true
    # Register it mostly to remove the translations once you delete an object
    self.has_many :translations, as: :resource, dependent: :destroy
  end

  fields.each do |field|
    # Add a marker to the schema of the application translations.
    RailsDbLocalize::add_to_schema(self, field)

    # Not sure if I would have to put dependent: :destroy here.
    self.has_many :"#{field}_translations", -> { where(field: field)  }, as: :resource

    # Making the magic happends.
    # I should really learn how to use the Reflection helpers in ActiveRecord, because
    # ruby eval is not the most readable stuff... :o)
    self.class_eval "      def \#{field}_translated (lang=nil)\n        lang ||= I18n.locale\n        RailsDbLocalize::TranslationCache.instance.get_translation_for(self.class, self.id, \"\#{field}\", lang, self.\#{field} )\n      end\n\n      def \#{field}_translated= args\n        if args.is_a?(Array)\n          value, lang = args\n        else\n          value = args\n          lang = I18n.locale\n        end\n\n        if self.id\n          translated = RailsDbLocalize::Translation.where(\n            resource_type: self.class.to_s, resource_id: self.id,  field: \"\#{field}\", lang: lang\n          ).first_or_create\n\n          translated.content = value\n\n          translated.save!\n        else\n          translations.build field: \"\#{field}\", lang: lang, content: value\n        end\n      end\n    CODE\n  end\nend\n", __FILE__, __LINE__ + 1