coding addicted
coding addicted

Reputation: 3430

Why this if statement fails with undefined local variable or method depending on the arguments order

I'm trying to understand why I get this error:

ActionView::Template::Error (undefined local variable or method ` current_user' for #<#<Class:0x007fc58d3b9ed0>:0x007fc58d4e92b0>

In my slim template I've got:

- if  current_user.admin? || current_user == @user 
  do something .....

It's an old app an usually only the admins dig enough to render this template. And when they do current_user.admin? part is working and no error is thrown. Today a user land to the template and current_user == @user should have return true and render the template because the user was legit but I got this error instead.

After some resolving attempts I figure out that if I inverted the arguments everything works as expected:

- if  current_user == @user  || current_user.admin?

I don't understand why I got the error and why the inversion of the arguments make this works?

UPDATE full error trace:

F, [2017-06-09T10:07:45.191191 #87199] FATAL -- :
ActionView::Template::Error (undefined local variable or method ` current_user' for #<#<Class:0x007fec49b70510>:0x007fec4e3a69b0>
Did you mean?  current_user
               @current_user):
    15:           =t('users.actions.new_user')
    16:
    17:       - if params[:controller] == 'admin/users' && params[:action] == 'show'
    18:         - if current_user.admin? || current_user.id == @user.id
    19:
    20:           li
    21:             = link_to main_app.edit_admin_user_path(@user), class: "leftMenuContent__listItem--sublink waves-effect waves-hsBlue" do
  app/views/layouts/admin/left_nav_content/_users.html.slim:18:in `_app_views_layouts_admin_left_nav_content__users_html_slim___2298613765678674655_70326381737720'
  app/views/layouts/admin/_left_content_navbar.html.slim:53:in `_app_views_layouts_admin__left_content_navbar_html_slim__3826854879423528297_70326437315280'
  app/views/layouts/admin/application.html.slim:43:in `_app_views_layouts_admin_application_html_slim___31832608430187073_70326348296780'

Update 2:

After digging I realize that the error was gone after a complete rewrite of the line. As mentioned in the comments I think the error is due to a "non real white space", this happened sometimes in some editors.

Upvotes: 0

Views: 122

Answers (1)

Michael Gorman
Michael Gorman

Reputation: 1077

What you are seeing is the results of short circuit algorithm:

In an || statement if the first argument is true, it doesn't bother checking the second.

In an && statement if the first argument is false, it doesn't bother checking the second.

It looks like something in admin? is attempting to call current_user function or variable that is not defined in the scope of admin?

Upvotes: 3

Related Questions