Build RSS feeds with Rails

I started a new position at a company called Modern Message last Monday. I’ll cover how to build RSS feeds in the Rails framework in this post.

One of my first tasks was to build a integration with Contentful (https://www.contentful.com/). A bit of a random side note, but Contentful is a blogging platform like WordPress that happens to be focus on API first interface. Thus, for developers who don’t want to build their own blogging platform in their applications, platforms like Contentful can be useful as they provide an interface to write blog posts and an API to consume your blog posts. I’ve never heard of a service like this, so I did some research into it and it looks like this is a new software niche that’s becoming popular these days.

Back to the main topic, one of the feature requests in the Contentful integration project was to expose an RSS feed that the public can consume. I’ll go over how to quickly build one in this post.

Let’s say that we have a model called Book and we want to expose all books that we have. The ActiveRecord model looks something like this.

And our corresponding standard Rails controller looks something like this.

And our config/routes.rb file looks something like this.

Fairly simple so far right? It gets simpler.

In our BooksController, we need to add a block to detect which http request formats our BooksController#index route will respond to. We want it to respond to both html and rss formats. html format because I’m assuming that you already have a corresponding HTML page for the index route. rss format to respond specifically to return rss feeds that the client applications can consume. Let’s modify our BooksController to look like this.

Now, create a new rss feed file at app/views/books/index.rss.builder. This file build the RSS feed that your clients will consume.

Now, if make a HTTP request to the BooksController#index endpoint with the rss format, you will get a response that looks something like this.

And that just about covers how to build RSS feeds within the context of Ruby on Rails!

About the Author Chris Jeon

Software developer currently focusing on Android development.