How to improve setting and getting temp variables around a block of code?
-
31-05-2021 - |
Question
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?
Solution
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