简体   繁体   English

Rails:如何在助手或控制器外部访问请求对象?

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

In my application_helper.rb file I have a function like this: 在我的application_helper.rb文件中,我有一个这样的函数:

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. 因此,我将此代码放在lib/目录中的实用程序函数文件中。 However, this did not work: I got complaints about request not being defined. 但是,这不起作用:我收到了关于request没有被定义的投诉。

How can I access the request object in a file in the lib/ directory? 如何访问lib/目录中的文件中的request对象?

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. 似乎您可能想要检查它是否是控制器中的internal_request(如果您在视图中需要它,请将其标记为控制器中的helper_method),然后告诉您的模型它是internal_request。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM