简体   繁体   English

我可以检查控制器是否从 Rails 中的 AMP 页面调用?

[英]Can I Check if a Controller is Being Called from an AMP page in Rails?

I'm starting to implement AMP pages in my Rails 5.2 app.我开始在我的 Rails 5.2 应用程序中实现 AMP 页面。 On desktop, I'm using the Will Paginate gem.在桌面上,我使用 Will Paginate gem。

However, with AMP I'm using the framework's infinite scroll JS, and I don't want to paginate the results.但是,对于 AMP,我使用的是框架的无限滚动 JS,我不想对结果进行分页。

So in the controller action, I want to determine if the user is viewing an AMP page (the URL ends with .amp ) to determine what I have for this line (include paginate or exclude):因此,在控制器操作中,我想确定用户是否正在查看 AMP 页面(URL 以.amp )以确定我对这一行的内容(包括分页或排除):

@products = @products.order('price DESC, RANDOM()').paginate(page: params[:page], per_page: 24)

How do I do this?我该怎么做呢?

The simple solution is just test request.format .简单的解决方案就是测试request.format So you could write所以你可以写

if request.format == :amp 
  # do not paginate
else
  # all other formats we paginate
end 

But inside a controller, we can also use an explicit respond_to block:但是在控制器内部,我们也可以使用显式respond_to块:

def index
  respond_to do |format|
    format.amp do 
      @products = @products.order('price DESC, RANDOM()')
    end 
    format.html do 
      @products = @products.order('price DESC, RANDOM()').paginate(page: params[:page], per_page: 24)
    end 
  end
end 

This will explicitly specify all the formats the controller method accepts and responds to.这将明确指定控制器方法接受和响应的所有格式。

As you probably already do, but you will have to provide a view for index.amp and a index.html .您可能已经这样做了,但是您必须为index.ampindex.html提供一个视图。

To be clear: this will also block all non-specified formats!需要明确的是:这也将阻止所有非指定格式! Eg retrieving a index.json will get a 405 Not allowed.例如,检索index.json将得到 405 Not allowed。

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

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