Dave Perrett

Rails NameError

programming, rails, ruby, web

If you’re getting NameError (uninitialized constant UnknownAction) using UnknownAction in the ‘rescue_action_in_public’ method, try to use the full reference (::ActionController::UnknownAction) instead of ActionController::UnknownAction.

For example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class ApplicationController < ActionController::Base

  attr_accessor :auth_err

  #--------------------------------------------
  # rescue_action_in_public()
  def rescue_action_in_public(exception)
    case exception
      when ActiveRecord::RecordNotFound
        unauthorised_action RecordNotFoundError
      when ::ActionController::UnknownAction
        unauthorised_action PageNotFoundError
      else
        log_error(exception)
        redirect_to('/500.html')
      end
  end



  #--------------------------------------------
  # unauthorised_action()
  def unauthorised_action(details=nil)
    # If one unauthorised_action has already occurred, don't need to log the rest
    return false if self.auth_err

    # Log the unauthorised_action
    user = "Unknown user"
    user = "User '" + @session[:user].login + "'" if @session[:user]
    msg = user + " denied access to '" + controller_name + "/" + action_name + "'"
    msg += " (" + details + ")" if details
    logger.error(msg)
    self.auth_err = true
    redirect_to('/404.html') and return false
  rescue
    self.auth_err = true
    return false
  end

end