Metalopholus - 1 year ago 43
Ruby Question

# New project with "rails new --api" -- missing ActionDispatch::Request

I'm trying to access the request object in app/controllers/application_controller.rb. My code is:

class ApplicationController < ActionController::API
include ActionView::Layouts
include ActionController::RequestForgeryProtection

protect_from_forgery

private

unless logged_in?
logger.log "#{request}"
end
end

def logged_in?
false
end
end


This results in the error:

comparison of String with 0 failed, highlighting the line logger.log "#{request}"


I thought it was a problem with the middleware not being loaded, so I tried to load it in config/application.rb:

config.middleware.use ActionDispatch::Request


But this results in another error:

undefined method 'call' for ActionDispatch::Request


I seem to keep having to add things back in since I used the --api option and it strips a lot of things out. But I don't know how to add back in access to the request option. Any help?

It looks like you are mis-using logger.log. In the simple example below, I have outlined three ways to approach this. If you want to use logger.log, you need to specify at minimum a severity level. That is the source of the comparison of String with 0 failed message you are receiving.

class ApplicationController < ActionController::API
before_action :log_request

def log_request
logger.log request                     # This doesn't work
logger.info("#{request}")              # This works
logger.log(Logger::WARN,"#{request}")  # This works
end

end


Valid levels are: FATAL, ERROR, WARN, INFO, DEBUG.

Reference: http://ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/Logger.html#method-i-add (logger.log is an alias for logger.add)

Logger#add(severity, message = nil, progname = nil) { ... }