Rails: how can I access the request object outside a helper or controller?

烂漫一生 提交于 2019-12-23 08:07:49

问题


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:


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.



来源:https://stackoverflow.com/questions/2576725/rails-how-can-i-access-the-request-object-outside-a-helper-or-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!