0

I am using Ruby on Rails v3.2.2 and globalize3 v0.2.0 ruby-gems. Since I would like to update translation data for an object (so to store proper data by using globalize3) I am using the following code in my controller file:

# Note how I set locale variables.
def update
  temp_locale = I18n.locale
  I18n.locale = 'it' # 'it' stands for italian

  @article = Article.find(params[:id])

  respond_to do |format|
    if @article.update_attributes(params[:article])
      format.html { redirect_to article_path(@article), notice: 'Article was successfully updated.' }
    else
      format.html { render action: "edit" }
    end
  end

  I18n.locale = temp_locale
end

The above code works as expected (that is, it updates translated data in the database for the italian language), but I think the way I am setting local variables is wrong, or at least not right at all or, maybe, not maintenable/readable. There is a way to improve that? Or, generally speaking, there is a way to improve setting and getting temp variables around a block of code? What do you advice about?

Backo
  • 18,291
  • 27
  • 103
  • 170

1 Answers1

1

I looked in the code for the i18n and found this:

I18n.with_locale('it') do
  # Italian stuff
end

It even validates your the input and employs an ensure clause to recover in case the black raises an error.

Here's the documentation: http://rubydoc.info/docs/rails/2.3.8/I18n.with_locale

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • Is the `with_locale` method available for the I18n gem included in Ruby on Rails v3.2.2? or it is available only for Ruby on Rails 2.3.8? – Backo Apr 14 '12 at 02:41
  • I thought that I18n was a separate gem, actually. Maybe it was part of Rails during 2.x, but it's separate in Rails 3. I would suspect that they wouldn't have made this change in a minor revision, but try it out if you have 3.2.2, or try upgrading (minor numbers represent bugfixes, at least in Rails). Also, you can use the qwandry gem to examine the source code to see if the method is there. – Brian Underwood Apr 15 '12 at 10:38