Rails: how can I access the request object outside

2019-06-17 19:27发布

In my application_helper.rb file I have a function like this:

def internal_request?
  server_name = request.env['SERVER_NAME']
  [plus more code...]
end

This function is needed in controllers, models, and views. So, I put this code in a utility function file in the lib/ directory. However, this did not work: I got complaints about request not being defined.

How can I access the request object in a file in the lib/ directory?

1条回答
冷血范
2楼-- · 2019-06-17 19:56

The simplest thing that would seem to work here is to pass the request object to the method.

def internal_request?(request)
 server_name = request.env['SERVER_NAME']
 [plus more code...]
end

The assumption is when ever this method is being called a request has been made, and that you can pass it to the method.

I am trying to think of a scenario where a model would need to call this method directly. Seems more likely that you might want to check if this was an internal_request in your controller (mark it as a helper_method in your controller if you need it in your view), and then tell your model it was an internal_request.

查看更多
登录 后发表回答