Quickstart with YQL and HTTParty with Rails

YQL makes it super-easy to consume data in your web app through a unified SQL-like API. And HTTParty by John Nunemakers makes HTTP really easy. A perfect match.

In environment.rb:

config.gem 'httparty'

Now, just create a model. Be sure to use the public endpoint for now, as the others need oauth authentication.

class News 
include HTTParty
base_uri 'http://query.yahooapis.com/v1/public/yql'

def self.new_york_news
self.get("", :query => {:q => 'select title, abstract, url from search.news where query = "%New York%"',
:format => 'json'})

def self.new_york_news_hash

In you controller:

class NewsController < ApplicationController
def index
@news = News.new_york_news_hash

And your view (for example):

<h1>New York News</h1>
<% @news.each do |news_item| %>
<% content_tag :h2 do %>
<%= link_to news_item["title"], news_item["url"] %> 
<% end %>
<% content_tag :div do  %>
<% content_tag :p do %>
<%= news_item["abstract"]%>
<% end %>
<% end %>
<%end %>

Be sure to check the API docs of YQL for many other options and watch the excellent screencasts by Christian Heilmann in the YUI theater and elsewhere. The possibilities are endless.

Posted: 05 August 2010

comments powered by Disqus