Rails:如何在帮助程序或控制器外部访问请求对象? [英] Rails: how can I access the request object outside a helper or controller?

查看:81
本文介绍了Rails:如何在帮助程序或控制器外部访问请求对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的application_helper.rb文件中,我具有如下功能:

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

控制器,模型和视图中需要此功能.因此,我将此代码放在lib/目录中的实用程序功能文件中.但是,这行不通:我收到有关未定义request的投诉.

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.

如何访问lib/目录中文件中的request对象?

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

推荐答案

在这里似乎最简单的方法是将请求对象传递给方法.

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.

我正在尝试考虑一个模型需要直接调用此方法的情况.似乎更有可能要检查这是否是控制器中的internal_request(如果在视图中需要,请在控制器中将其标记为helper_method),然后告诉模型这是internal_request.

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.

这篇关于Rails:如何在帮助程序或控制器外部访问请求对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆