Quickstart with YQL and HTTParty with Rails

Ruby on Rails, YQL 1 Comment »

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’

      })
  end

  def self.new_york_news_hash
    self.new_york_news.parsed_response["query"]["results"]["result"]
  end
 
end

In you controller:

class NewsController < ApplicationController

  def index
    @news = News.new_york_news_hash
  end

end

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.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in