Contentful integration for Rails


The following is a tutorial on how to easily integrate Contentful into a Ruby on Rails application. The following blog post assumes that you have created a Content Model inside of Contentful and added some pieces of content.

Installation #

Include the following line in your Gemfile and then execute bundle install:

gem 'contentful'

Head to the API Keys section under setting and copy both your Space ID and Content Delivery API - access token. We will set these as environment variables using the names CONTENTFUL_SPACE_ID and CONTENTFUL_ACCESS_TOKEN respectively.

The helper function #

Within my lib folder I have created a ContentfulHelper which will essentially act as the bridge that talks to the Contentful service.

require 'contentful'

module ContentfulHelper

  @contentful ||= Contentful::Client.new(
    access_token: ENV['CONTENTFUL_ACCESS_TOKEN'],
    dynamic_entries: :auto,
    raise_errors: true

  def self.all_articles
    @contentful.entries(content_type: 'article')


Consuming your Content #

The code bellow is for the integration test which will be able to pull in data from Contentful. Use a similar technique in your controller to grab data from Contentful.

require 'test_helper'
require 'contentful_helper'

class ContentfulTest < ActionDispatch::IntegrationTest
  include ContentfulHelper 

  test "get an array of all the articles" do
    res = ContentfulHelper.all_articles
    assert_not_equal(0, res.length)

  test "get content for the first article" do
    res = ContentfulHelper.all_articles

    first = res.items.first

    # This test assumes the following fields on your content model:
    title = first.fields[:title]
    author = first.fields[:author]

    assert_equal("some id", first.id)
    assert_equal("Some title of a blog post here", title)
    assert_equal("Shahzeb", author)


The next steps #

Now that you can successfully fetch content from the Contentful service, you can send the data from your Controller down into your views. As an advanced concept, you should consider caching data from Contentful into a cache (such as Redis) so that your application isn’t repeatedly reaching out to Contentful.


Now read this

3 apps that every college student should use

These apps will super-charge your life. They’ll make you more productive than you’ve ever been. They’ll pretty much write that 900 word essay you’ve been procrastinating on. Here’s a list of 3 incredibly sexy apps that are available on... Continue →