Module: HasTranslations::ModelAdditions::ClassMethods

Defined in:
lib/has_translations/model_additions.rb

Instance Method Summary collapse

Instance Method Details

#has_translations(*attrs) ⇒ 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/has_translations/model_additions.rb', line 10

def has_translations(*attrs)
  new_options = attrs.extract_options!
  options = {
    fallback: false,
    reader: true,
    writer: false,
    nil: '',
    autosave: new_options[:writer],
    translation_class: nil
  }.merge(new_options)

  translation_class_name = options[:translation_class].try(:name) || "#{self.model_name}Translation"
  options[:translation_class] ||= translation_class_name.constantize

  options.assert_valid_keys(
    [
      :fallback,
      :reader,
      :writer,
      :nil,
      :inverse_of,
      :autosave,
      :translation_class,
      :foreign_key
    ]
  )

  belongs_to = self.model_name.to_s.demodulize.underscore.to_sym

  class_attribute :has_translations_options
  self.has_translations_options = options

  # associations, validations and scope definitions
  options[:translation_class].belongs_to(belongs_to, foreign_key: options[:foreign_key])
  has_many(
    :translations,
    class_name: translation_class_name,
    dependent: :destroy,
    autosave: options[:autosave],
    inverse_of: options[:inverse_of],
    foreign_key: options[:foreign_key]
  )
  options[:translation_class].validates(
    :locale,
    presence: true,
    uniqueness: {scope: (options[:foreign_key] || "#{belongs_to}_id").to_sym}
  )

  # Optionals delegated readers
  if options[:reader]
    attrs.each do |name|
      send :define_method, name do |*args|
        locale = args.first || I18n.locale
        translation = self.translation(locale)
        translation.try(name) || has_translations_options[:nil]
      end
    end
  end

  # Optionals delegated writers
  if options[:writer]
    attrs.each do |name|
      send :define_method, "#{name}_before_type_cast" do
        translation = self.translation(I18n.locale, false)
        translation.try(name)
      end

      send :define_method, "#{name}=" do |value|
        translation = find_or_build_translation(I18n.locale)
        translation.send(:"#{name}=", value)
      end
    end
  end
end

#translated(locale) ⇒ Object



6
7
8
# File 'lib/has_translations/model_additions.rb', line 6

def translated(locale)
  where("#{self.has_translations_options[:translation_class].table_name}.locale = ?", locale).joins(:translations)
end