Module: ZLocalize::Translatable::AttachedTranslations::InstanceMethods

Defined in:
lib/zlocalize/rails/attached_translations.rb

Instance Method Summary collapse

Instance Method Details

#add_translation(name, locale, value) ⇒ Object



78
79
80
81
82
83
84
85
# File 'lib/zlocalize/rails/attached_translations.rb', line 78

def add_translation(name,locale,value)
  if tr = find_translation(name,locale)
    tr.value = value.to_s
  else
    tr = translations.build(:translated => self, :name => name.to_s, :locale => locale.to_s, :value => value.to_s)
  end
  tr
end

#insert_translations(locales = {}) ⇒ Object

convenience method to accept a Hash containing the translations for multiple columns and locales. locales must have the locales as keys and its value is another Hash of name-value pairs. Example:

@article.insert_translations(
     { 'en' => { 'title'    => "What's new this week",
                 'synopsis' => "Learn what has happened this week in our little world"},
       'fr' => { 'title'    => "Quoi de neuf cette semaine",
                 'synopsis' => "Apprenez tout sur ce qui s'est passé cette semaine dans notre petit monde" }

If you have user-generated content, for example, you can quickly create a form to edit the translatable content as follows: in the view:

<label>Title in English</label>
<%= text_field 'translations[en][title]', @article.translate('title','en') %>
<label>Title in French</label>
<%= text_field 'translations[fr][title]', @article.translate('title','fr') %>

in the controller:

def update

...
@article.insert_translations(params['translations'])
@article.save

end

make sure your content is sanitized!



114
115
116
117
118
119
120
121
122
# File 'lib/zlocalize/rails/attached_translations.rb', line 114

def insert_translations(locales = {})
  Translation.transaction do
    locales.each do |locale,terms|
      terms.each do |name,value|
        add_translation(name,locale,value)
      end
    end
  end
end

#translate(attr_name, locale = nil, fetch_default = true) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/zlocalize/rails/attached_translations.rb', line 63

def translate(attr_name,locale = nil, fetch_default = true)
  locale ||= ZLocalize.locale
  if tr = find_translation(attr_name,locale)
    return tr.value
  else
    unless (default_locale = evaluate_default_locale_for_translations).blank?
      if default_locale.to_s != locale.to_s
        if tr = find_translation(attr_name,default_locale)
          return tr.value
        end
      end
    end
  end
end