Home undefined local variable or method 'request' - in controller helper
Reply: 1

undefined local variable or method 'request' - in controller helper

Joe Masilotti
1#
Joe Masilotti Published in 2018-02-12 13:19:39Z

We have been seeing an increasing number of errors with the same call sight:

NameError: undefined local variable or method 'request' for :false:Symbol

They are all raising from an authentication helper located in lib. This method runs successfully 99% of the time (we know because it logs you in without issue). However, for a very small number of requests the request object can't be found, as shown in the error message.

We have been seeing this for a variety of user agents. For what it's worth, ApplicationController includes (via include) the helper in question.

Is there any common debugging techniques or known issues where request can be missing during a Rails request? If it helps, the same occurs for cookies.

The relevant bits of code:

# lib/authenticated_system.rb
module AuthenticatedSystem
  def logged_in?
    current_user != :false
  end

  def current_user
    @current_user ||= login_via_cookie || login_via_url || :false
    @current_user
  end

  def login_via_cookie
    Rails.logger.info "IP: #{request.ip}" # example of accessing request
    if token = cookies[:web_token]
      User.find_by(auth_token: token)
    end
  end

  def login_via_url
    # return User or nil
  end
end

# app/controllers//foo_controller.rb
class FooController < ApplicationController
  include Alerting

  def show
    log_alert(current_user)
  end
end

# lib/alerting.rb
module Alerting
  def log_alert(user)
    Rails.logger.info "User: #{user.id}" # example of accessing user
  end
end
SteveTurczyn
2#
SteveTurczyn Reply to 2018-02-13 11:26:56Z

This code isn't correct...

@current_user ||= login_via_cookie || login_via_url || :false

It's setting @current_user to the symbol :false

Better to set it to the object false or still better, let it default to nil

@current_user ||= (login_via_cookie || login_via_url)

and change the logged_in? to...

def logged_in?
  !!current_user
end

At some point in one of your lib modules I suspect you're calling current_user.request which is causing the problem.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.295456 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO