Register now and start sharing your code snippets.
-->

Example of how to fetch a URL with Net:HTTP and Ruby

Ruby posted 7 months ago by christian

   1  require 'net/http'
   2  require 'net/https'
   3  
   4  url = URI.parse('http://www.google.com/yo?query=yahoo')
   5  
   6  http = Net::HTTP.new(url.host, url.port)
   7  
   8  http.open_timeout = http.read_timeout = 10  # Set open and read timeout to 10 seconds
   9  http.use_ssl = (url.scheme == "https")
  10         
  11  headers = {
  12    'User-Agent'          => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
  13    'If-Modified-Since'   => '',
  14    'If-None-Match'       => ''
  15  }
  16  
  17  # Note to self, use request_uri not path: http://www.ruby-doc.org/core/classes/URI/HTTP.html#M004934
  18  response, body = http.get(url.request_uri, headers)
  19  
  20  puts response.code
  21  puts response.message
  22  
  23  response.each {|key, val| puts key + ' = ' + val}

Tagged net, http, ruby, example, headers

Valid RSS 2.0 Feed Template for Rails

HTML (Rails) posted about 1 year ago by christian

Here’s the template, modify it to fit your needs. I know there are plugins and other ways of doing this, but I hate code that gets too abstract:

   1  <?xml version="1.0"?>
   2  <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
   3    <channel>
   4      <atom:link href="http://xxxxxxx" rel="self" type="application/rss+xml" />
   5      <title>Code Snippets - Aktagon</title>
   6      <link>http://snippets.aktagon.com/</link>
   7      <description>Share your code with the world. Allow others to review and comment.</description>
   8      <language>en-us</language>
   9      <pubDate><%= @snippets[0].created_at.rfc822 %></pubDate>
  10      <lastBuildDate><%= @snippets[0].created_at.rfc822 %></lastBuildDate>
  11      <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  12      <generator>Aktagon Snippets</generator>
  13   <% for snippet in @snippets %>
  14      <item>
  15        <title><![CDATA[<%= snippet.title %>]]></title>
  16        <link><%= snippet_url(snippet) %></link>
  17        <description><![CDATA[<%= snippet.rendered_body %>]]></description>
  18        <pubDate><%= @snippets[0].created_at.rfc822 %></pubDate>
  19        <guid><%= snippet_url(snippet) %></guid>
  20  	  <% for tag in snippet.tags%>
  21  		<category domain="http://snippets.aktagon.com/snippets"><![CDATA[<%= tag.name %>]]></category>
  22  	  <% end%>
  23      </item>
  24  <% end %>
  25    </channel>
  26  </rss>
  27  

Remember to serve the feed with the correct HTTP headers.

It also helps to have an auto-discovery tag inside the head tag:

   1  <link rel="alternate" type="application/rss+xml" title="RSS feed" href="http://<%= request.host %>/rss/" />

Tagged ruby, rails, rss2.0, feed, rss, template, example