简体   繁体   中英

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. On desktop, I'm using the Will Paginate gem.

However, with AMP I'm using the framework's infinite scroll JS, and I don't want to paginate the results.

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):

@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 . 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:

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 .

To be clear: this will also block all non-specified formats! Eg retrieving a index.json will get a 405 Not allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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