我正在尝试创建一个使用Google Custom Search API
Sinatra
的简单应用。这是代码:
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
索引视图正确运行并将数据传递到/ ssearch视图(我已经在Google CSE API
上进行了测试并完成了搜索)。但我不知道如何在items变量中显示链接内容。我只需要稍后将使用的搜索结果链接。
这是/ ssearch视图:
<h3><%= items["items"].each do |x| %>
<%= x["links"] %>
<%= end %>
</h3>
但服务器返回:
views / ssearch.erb:1:语法错误,意外')' ... [“items”] [“link”]。每个都做| x | ).to_s); @ _out_buf.concat“\ n”... ^
我会理解如何正确地对这些项目进行迭代,有人可以帮我吗?奇怪的事情(对我而言,因为我确信我的错误不是那么奇怪,可能是由于我的新生),如果我写下面的代码:
<h3><%= items["items"][0]["link"] %></h3>
我获得了正确的结果(但显然只是0指数)。
答案 0 :(得分:3)
<%= end %>
无法使用(并且没有意义),请使用<% end %>
:
<% items["items"].each do |x| %>
<%= x["links"] %>
<% end %>