繁体   English   中英

在Rails中,是否可以在类(而不是控制器)中调用request.request_uri?

[英]In Rails, is there a way to call request.request_uri in a class (not a controller)?

我正在使用Google Analytics(分析)API的Garb Ruby包装器为我的应用构建综合浏览量计数器。 这样做意味着在'lib'文件夹中创建一个新的Module,在其中创建如下所示的类:

#lib/Analyze.rb

...
class Report
  extend Garb::Resource
  metrics :pageviews
  dimensions :page_path
  filters :page_path.eql => '/' #the path of the page I instantiate this class on
end

#followed by a method for instantiating this class

我需要过滤器:page_path.eql =>作为我在其中调用方法的页面的路径。 我已经尝试过诸如request.request_uri或url_for(:action =>'show':controllers =>'users':id => params [:id])之类的事情,但是不知道如何在此类中指定页面路径定义。

这将破坏MVC封装-我认为您应该在application_controller中创建一个before过滤器,该过滤器会将您需要的请求数据传递给类。

编辑

如果您想为特定页面建立一次性报告,我认为您需要执行以下操作:

profile = Garb::Profile.first('UA-XXXX-XX')

report = Garb::Report.new(profile)
report.metrics :pageviews
report.dimensions :page_path
report.filters :page_path.eql => request.request_uri 

report.results

再说一次,如果您在每个页面上都这样,我认为一个前置过滤器将是明智的。 可以肯定的是,它将大大降低您的应用程序运行速度。

在文档中对此进行了介绍。

暂无
暂无

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

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