Thursday, September 18, 2008

BOSSMan: Yahoo! BOSS + Ruby

Con el lanzamiento de Yahoo! BOSS ha llegado BOSSMan, un plugin/gem creado por el desarrollador Jay Pignata que permite interactuar con éste nuevo API de Yahoo! de una forma bien simple, como son las cosas en Ruby.

Para ver como funciona he creado un buscador de noticias bilingüe utilizando Ruby on Rails, http://yahoosearch.heroku.com. Aquí está el código:


Instalación de BOSSMan:
gem sources -a http://gems.github.com
gem install jpignata-bossman

controllers/search_controller.rb

require 'rubygems'
require 'bossman'
include BOSSMan

class SearchController < ApplicationController
def index
@results = Array.new
@language = [true, false]
if (request.post? and params[:query] != "")
BOSSMan.application_id = "<Your Application ID>"
@news = BOSSMan::Search.news(params[:query], {
:region => 'us',
:lang => params[:language],
:age => "7d",
:count => 10 })
@results = @news.results if @news.count != "0"
@language = [false, true] if params[:language] == 'es'
end
end
end


views/layout/application.html.erb

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html>
<head>
<title>News from Yahoo! by BOSSMan</title>
<%= stylesheet_link_tag 'style' %>
</head>
<body>
<div id='header'>
<h1>News from Yahoo! by BOSSMan</h1>
</div>
<div id="content">
<%= yield %>
</div>
<div id="footer">
<div id="altnav">
<%= link_to 'Home', '/' %> -
<%= mail_to 'contact@yahoosearch.com', 'Contact' %>
</div>
Yahoo! Search by BOSSMan
</div>
</body>
</html>


views/search/index.html.erb

<div id="form">
<% form_tag :action => 'index' do%>
<%= radio_button_tag 'language', 'en', @language[0], {} %>
English
<%= radio_button_tag 'language', 'es', @language[1], {} %>
Español<br/>
<%= text_field_tag 'query', params[:query], :size => '50' %>
<%= submit_tag 'Search' %>
<% end %>
</div>
<% if @results.length != 0 %>
<div id="results">
<%= render :partial => 'results', :collection => @results %>
</div>
<% end %>


views/search/_results.html.erb

<div id="result">
<h4><%= link_to results.title, results.url %></h4>
<p><%= results.abstract %></p>
<h6><%= link_to results.source, results.sourceurl %>
<%= "#{results.date} #{results.time}" %></h6>
</div>


public/stylesheets/style.css

body {
background-color: #5a8f5e;
font-family: Verdana;
}

#header{
text-align: center;
}

#content {
background-color: white;
border: 1px solid black;
width: 750px;
margin: 20px auto;
padding: 20px;
}

#form {
text-align: center;
}

#results{
margin-top: 20px;
padding: 5px 20px 5px 20px;
border: 1px solid gray;
}

#result h4 {
margin-bottom: 5px;
}

#result h6 {
margin-top: 5px;
}

#result p {
margin-top: 0px;
margin-bottom: 0px;
}

#footer {
margin: 0px auto;
width: 750px;
color: #c9c9c9;
line-height: 20px;
}

#footer a {
color: #c9c9c9;
text-decoration: none;
}

#footer a:hover {
color: #000000;
}

#footer #altnav {
width: 350px;
float: right;
text-align: right;
}

No comments: