Search code examples
ruby-on-rails-3localizationrefinerycmsrails-i18n

Locale does not switch while iterating in Rails


I have extended RefineryCMS blog/admin/posts controller with Export action, which export post to xml and save it to file. I need export all translated versions of post. When I click export it saves all files, but all files have same locale.

Is it anything wrong with my code:

def generate_xml_by_locales
  translated_locales.each do |l|
    ::I18n.locale = l
    file = File.new("blog_#{l}.xml", "wb")
    xml = Builder::XmlMarkup.new :target => file
    xml.instruct!
    xml.blog do
      xml.title post.title
      xml.description "Sixteenth installment of development diary"
      xml.language l.to_s
      xml.author "Dan"
      xml.date post.created_at
      xml.category "diary"
      xml.text post.body
    end
    file.close
  end 
end

Thanks for help.


Solution

  • I did one modification, which work just fine. Instead of changing locale via I18n.locale I use translations.where(locale: lang).first . Don't know if it is the best solution, but it just works.

    Refactored code:

    def generate_xml_by_locales
      translated_locales.each do |lang|
        generate_xml(translations.where(locale: lang).first, lang)
      end
    end
    
    def generate_xml post, lang
      file = File.new("blog_#{lang}.xml", "wb")
      xml = Builder::XmlMarkup.new :target => file
      xml.instruct!
      xml.blog do
        xml.title post.title
        xml.description "Sixteenth installment of development diary"
        xml.language lang.to_s
        xml.author "Dan"
        xml.date post.created_at
        xml.category "diary"
        xml.text post.body
      end
      file.close
    end