By David Litvak, on Apr 21, 2016

Build Contentful-driven Ruby apps with Sinatra and Rails

As we consider Ruby on Rails and Sinatra the most popular Ruby frameworks out there, we assume that many Ruby developers across the world would love to integrate Contentful into their apps in some simple and elegant way.

In this spirit we wrote two demo apps – one for each framework. Each app displays a catalogue of products, quite similar to one you would typically see at an online shop. (The content is coming from our product catalogue template.)

The tutorial for each app explains the thinking behind every step and shows how to use the Contentful Ruby SDK inside a new app – or how to integrate it with your existing applications. We demonstrate several different approaches – the final choice is up to you and depends primarily on the complexity of your project.

Ruby on Rails demo

Using ActiveRecord as the storage abstraction layer for the API and space credentials, we created a customizable Product Demo. Our SDK Client then uses these credentials and outputs all the content for the website.

rails product demo

Get the Rails demo app

Sinatra demo

Sinatra doesn't come with built-in database abstractions, so we went for a slightly different approach, sending the credentials as parameters in the URL. Our routes then handle all the necessary parameters and delegate them to our SDK.

This is all the code that makes it work:

ruby
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require 'sinatra/base'
require 'contentful'

class ContentfulDemoApp < Sinatra::Application
  set :views, settings.root + '/templates'

  get '/' do
    slim :index
  end

  get '/space/:space/token/:token/content_type/:content_type' do
    slim(
      :products,
      locals: {
        products: contentful(
          params[:space],
          params[:token]
        ).entries(
          content_type: params[:content_type],
          include: 2
        )
      }
    )
  end

  private

  def contentful(space, access_token)
    @client ||= Contentful::Client.new(
      space: space,
      access_token: access_token,
      dynamic_entries: :auto,
      raise_errors: true
    )
  end
end

Get the Sinatra demo app

Pull requests are welcome

We'd love to see your ideas, too! Please submit what's on your mind in the shape of PRs or issues.

More tutorials

Feel free to also look at our static site generators examples with Middleman and Jekyll.

David Litvak

David is a Ruby and Python evangelist, agile devotee, frustrated sports legend, and developer evangelist at Contentful. He spends most of his days either coding or slaying orcs and beasts in his favorite role playing games. You can follow him on Twitter or on Github.