开发者

Google custom search API with pagination

开发者 https://www.devze.com 2023-03-15 00:33 出处:网络
I have this method that puts the links of the 10 results from the Google custom search API into an array:

I have this method that puts the links of the 10 results from the Google custom search API into an array:

require 'json'
require 'open-uri'

def create
    search = params[:search][:search]
    base_url = "https://www.googleapis.com/customsearch/v1?"

    stream = open("#{base_url}key=XXXXXXXXXXXXX&cx=XXXXXXXXXX&q=#{search}&start=#{i}&alt=json")
    raise 'web service error' if (stream.status.first != '200')

    result = JSON.parse(stream.read)

    @new = []
    result['items'].each do |r|
      @new << r['link']
    end
end

and my view:

<% @new.each do |link| %>
    <p><%= link %></p>
<% end %>

I'm having trouble figuring out how to add pagination with this so that on the second page would return the next 10 results. I'm using the Kaminari gem for pagination.

I want for when a user clicks a link to another page, I fetch the next 10 results from Google's API. You can do this with the API's start parameter that specifies the first result to start with, which I pass as i. I was thinking of doing开发者_StackOverflow something like this:

i = (params[:page] - 1) * 10 + 1

where params[:page] is the current page number, but for some reason it is undefined. Also I'm unsure about how to setup pagination for an array that is not an AR object, and what would go in my view. I'd appreciate any help, and feel free to use any pagination gem you know.


How are you setting params[page]? It needs to be passed in with the other parameters in your request in some way.

Perhaps you need something like this in your controller:

@page = params[:page] || 1
i = (@page - 1) * PER_PAGE + 1

stream = open("#{base_url}key=XXXXXXXXXXXXX&cx=XXXXXXXXXX&q=#{search}&start=#{i}&alt=json")
raise 'web service error' if (stream.status.first != '200')

result = JSON.parse(stream.read)
@new = result['items'].map{|r| r['link']}

In your view you need to make sure that you are passing the page via the query parameter in the link to fetch the next set of results. Most likely that you would want to return @page + 1.

Handling pagination with non ActiveRecord objects depends on your pagination library. You might want to check out how will_paginate handles this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号