MonkTools
MonkTools

Reputation: 45

Ruby does not iterate over Google Custom Search response items

I'm trying to create a simple app that uses Google Custom Search API with Sinatra. Here's the code:

require 'rubygems'
require 'sinatra'
require 'google/api_client'

def extract_cse_info(thekey)
    client = Google::APIClient.new(:key => 'my_api_key', :authorization => nil)
    search = client.discovered_api('customsearch')

    response = client.execute(
        :api_method => search.cse.list,
        :application_name => 'Sgoogle',
        :application_version => '0.1',
        :parameters => {
            'q' => thekey,
            'key' => 'my_api_key',
            'cx' => 'my_cx_id'
        }
    )
    return JSON.parse(response.body)
end


get '/' do 
    erb :index
end

post '/ssearch' do

    keyword = params[:key]

    items = extract_cse_info(keyword)

    erb :ssearch, :locals => { 'items' => items }
end

The index views run correctly and pass the data to the /ssearch view (I had tested on irb the Google CSE API too and it completes the search). But I don't know how to show the links content in the items variable. I just need the links of the search result that I'll use later.

This is the /ssearch view:

<h3><%= items["items"].each do |x| %>
    <%= x["links"] %>
    <%= end %>
</h3>

But the server returns:

views/ssearch.erb:1: syntax error, unexpected ')' ...["items"]["link"].each do |x| ).to_s); @_out_buf.concat "\n" ... ^

I would understand how to iterate correctly over that items, someone could help me please? The strange things (for me 'cause I am sure that my error is not so strange and probably is due to my newbity) is if I write the following code:

<h3><%= items["items"][0]["link"] %></h3>

I obtain the right result (but just for the 0 index obviously).

Upvotes: 1

Views: 111

Answers (1)

Stefan
Stefan

Reputation: 114188

<%= end %> doesn't work (and doesn't make sense), use <% end %>:

<% items["items"].each do |x| %>
  <%= x["links"] %>
<% end %>

Upvotes: 3

Related Questions