rubocop / rails-style-guide

A community-driven Ruby on Rails style guide
http://rails.rubystyle.guide
6.48k stars 1.06k forks source link

Suggestion: Add notes about returned value of ActiveRecord transaction #338

Open ydakuka opened 1 year ago

ydakuka commented 1 year ago

The following code raises NameError error, because the result variable is defined only in the transaction scope.

ActiveRecord::Base.transaction do
  result = 1
end

result # NameError: undefined local variable or method `result'

To fix it I need:

1) to define the result variable before the transaction block

result = nil

ActiveRecord::Base.transaction do
  result = 1
end

result

2) to assign transaction block to the result variable:

result =
  ActiveRecord::Base.transaction do
    1
  end

3) to replace local variable with instance variable:

ActiveRecord::Base.transaction do
  @result = 1
end

@result

Which way is better?