Gnerate RSS for your site in Rails

Posted: Thursday, March 18, 2010 | Posted by කේෂාන් | Keshan | Labels:
With the rapid development in world wide web it is obvious that we cannot go to every site we like in daily basis to check for its updates to eliminate that problem we have something called rss in web 2.0. as a developer it is a cool idea to generate rss for your site then your site readers can keep in touch with your web site or blog.

here i am going to explain how you could easily do it with Rails.

first i assume you have a rails project and have a controller called post(you can have whatever name but this example is based on a controller called posts) go to post_controller.rb in your Controllers directory and change the index method

 respond_to do |format|
      format.html
      format.xml  { render :xml => @posts }
      format.rss  { render :layout => false }
    end
  end

and then go to Views and add a file called index.rss.builder to posts view directory and the below content to that file(remember in RoR convention is over configuration so, be careful about naming conventions)

xml.instruct! :xml, :version => "1.0"
xml.rss :version => "2.0" do
  xml.channel do
    xml.title "posts"
    xml.description "Lots of posts"
    xml.link formatted_posts_url(:rss)

    for post in @posts
      xml.item do
        xml.title post.title
        xml.description post.body
        xml.pubDate post.created_at.to_s(:rfc822)
        xml.link formatted_post_url(post, :rss)
        xml.guid formatted_post_url(post, :rss)
      end
    end
  end
end


here we go it is done to view this you can start the server and go to http://localhost:3000/posts.rss

but it is better to add a link to the rss feeds to do it go to index.html.erb in Views, posts view directory and add the following line where you want to see the lnk

<%= link_to "RSS", formatted_posts_url(:rss) %> 


if you want to clarify anything do not hesitate to comment below
have fun !!

Kesh,

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...