Module: HasTranslations::ModelAdditions

Extended by:
ActiveSupport::Concern
Defined in:
lib/has_translations/model_additions.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#all_translationsObject



104
105
106
107
108
109
# File 'lib/has_translations/model_additions.rb', line 104

def all_translations
  t = I18n.available_locales.map do |locale|
    [locale, find_or_create_translation(locale)]
  end
  ActiveSupport::OrderedHash[t]
end

#find_or_build_translation(locale) ⇒ Object



92
93
94
95
96
97
# File 'lib/has_translations/model_additions.rb', line 92

def find_or_build_translation(locale)
  locale = locale.to_s
  (find_translation(locale) || self.translations.build).tap do |t|
    t.locale = locale
  end
end

#find_or_create_translation(locale) ⇒ Object



84
85
86
87
88
89
90
# File 'lib/has_translations/model_additions.rb', line 84

def find_or_create_translation(locale)
  locale = locale.to_s
  (find_translation(locale) || self.has_translations_options[:translation_class].new).tap do |t|
    t.locale = locale
    t.send(:"#{self.class.model_name.to_s.demodulize.underscore.to_sym}_id=", self.id)
  end
end

#find_translation(locale) ⇒ Object



115
116
117
118
# File 'lib/has_translations/model_additions.rb', line 115

def find_translation(locale)
  locale = locale.to_s
  translations.detect { |t| t.locale == locale }
end

#has_translation?(locale) ⇒ Boolean

Returns:

  • (Boolean)


111
112
113
# File 'lib/has_translations/model_additions.rb', line 111

def has_translation?(locale)
  find_translation(locale).present?
end

#translation(locale, fallback = ) ⇒ Object



99
100
101
102
# File 'lib/has_translations/model_additions.rb', line 99

def translation(locale, fallback=has_translations_options[:fallback])
  locale = locale.to_s
  find_translation(locale) || (fallback && !translations.blank? ? translations.detect { |t| t.locale == I18n.default_locale.to_s } || translations.first : nil)
end