4

TipSnippet: Create a RSS feed

 3 years ago
source link: https://www.devroom.io/2007/04/03/tipsnippet-create-a-rss-feed/?utm_campaign=Feed%3A+ariejan+%28ariejan%7Cdevroom.io%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

TipSnippet: Create a RSS feed

Posted: 2007-04-03 - Last updated: 2020-03-09

Tagged general rubyonrails features tipsnippets

RSS is hot! So, you want to fit your new Rails app with one too! That’s easy, of course, but you just need to know what to do.

This snippet will show you how to create an RSS feed form your RESTful articles. I’ll assume you know how to generate a resource named ‘article’ with a title, body and the default created_at and updated_at attributes.

You’ll first need to add a new collection to your resource in config/routes.rb

map.resources :articles, :collections => {:rss => :get}

This will expose your RSS feed as http://localhost:3000/articles;rss

Create a corresponding action in the articles controller in app/controllers/articles_controller.rb. This method fetches the ten latest articles.

def rss
  @articles = Article.find(:all, :limit => 10, :order => 'created_at DESC')
  render :layout => false
end

I assume you render your articles in a layout. The render method here prevents your layout from rendering to create a plain XML file (which is what an RSS feed is).

Next we create a view. This is not the regular RHTML you’re used to but RXML. This enables the XML generator which we’ll use to generate the RSS feed. Create app/views/articles/rss.rxml

xml.instruct! :xml, :version=>"1.0"
xml.rss(:version=>"2.0"){
  xml.channel{
    xml.title("My Great Blog")
    xml.link("http://www.example.com/")
    xml.description("My great blog about very interesting stuff!")
    xml.language('en-uk')
      for article in @articles
        xml.item do
          xml.title(article.title)
          xml.description(article.body)
          xml.author("[email protected]")
          xml.pubDate(article.created_at.strftime("%a, %d %b %Y %H:%M:%S %z"))
          xml.link(article_url(article))
          xml.guid(article_url(article))
        end
      end
  }
}

Well, that’s it. You now have a working RSS feed!

If you want to enable auto discovery, you should add the following line to the header of your layout. (Auto discovery enables that little RSS icon in the address bar of your browser.)

<%= auto_discovery_link_tag(:rss, :controller => 'articles', :action => 'rss') %>

Share and enjoy! Thank you.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK