Contentful integration for Rails

contentful-rails.jpg

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'],
    space: ENV['CONTENTFUL_SPACE_ID'],
    dynamic_entries: :auto,
    raise_errors: true
  )

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

end

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)
  end

  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)
  end

end

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.

 
7
Kudos
 
7
Kudos

Now read this

Easily log custom metrics to AWS CloudWatch

Recently, I wanted to track the amount of time that Sidekiq jobs were taking to execute on a production Rails environment. I wanted an easy way to be able to track the arguments for the Sidekiq job, the user that initiated the job, and... Continue →