Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Shadowing outer local variable in rubocop and how do I fix this?

I am running rubocop on rails and it gave me the message below.

W: Shadowing outer local variable - user.
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
                                                                    ^^^^

This is the code.

def self.from_omniauth(auth)
user = User.where(email: auth.info.email).first

if user
  return user
else
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.fullname = auth.info.name
    user.provider = auth.provider
    user.uid = auth.uid
    user.email = auth.info.email
    user.image = auth.info.image
    user.password = Devise.friendly_token[0, 20]
  end
end

end

like image 815
Anna_Natorilla Avatar asked Nov 16 '15 14:11

Anna_Natorilla


1 Answers

This means that the user provided as a block arguments will overwrite the user variable defined here user = User.where(email: auth.info.email).first

To overcome it you'll need to change the name of one of the variables. Either something like:

result = User.where...
return result if result    

Or:

where(provider: auth.provider, uid: auth.uid).first_or_create do |u|
  u.fullname = auth.info.name
  ...
end

Some more info: https://github.com/bbatsov/ruby-style-guide#no-shadowing

like image 117
Kamen Avatar answered Oct 05 '22 22:10

Kamen