Get Started with Ruby SDK and Live Preview
This guide will help you get started with Contentstack Ruby SDK to build apps powered by Contentstack.
Prerequisites
To get started with the Ruby SDK, you will need the following:
- Ruby version 2.0 or later
SDK Installation and Setup
To use the Ruby SDK, download it using the gem install command:
$ gem install contentstack
Let's get started with the implementation.
Initializing the Stack with Live Preview
Since the Live Preview Utils SDK is responsible for communication, you need to initialize it within your stack.
Use the following command to initialize the stack:
$client = Contentstack::Client.new("api_key", "delivery_token", "enviroment_name", {
live_preview: {
management_token: 'management_token',
enable: true,
host: 'api.contentstack.io',
}
})
Note: By default, the host parameter points to the North America endpoint. If your website is hosted on the European data center, then pass the European endpoint against the host parameter.
Add Custom Middleware
You need to add a custom middleware in the lib/middleware/contentstack_middelware.rb file.
Use the following code to get the Live Preview hash key:
class ContentstackMiddleware
def initialize(app)
@app = app
end
def call(env)
@req = Rack::Request.new(env)
// this will get live_preview hash and ContentType to request
$client.live_preview_query(@req.params)
@app.call(env)
end
end
Add Middleware in the Config File
To add a middleware in the config file, use the following code:
module AppName
class Application < Rails::Application
...
config.middleware.use CustomMiddleware
end
end
For Server-side Rendered Websites
To install and initialize the Live Preview Utils SDK, you can refer to our SSR Live Preview Setup documentation.
Query Request
Contentstack SDKs let you interact with the Content Delivery APIs and retrieve content from Contentstack. They are read-only in nature. The SDKs fetch and deliver content from the nearest server via Fastly, our powerful and robust CDN.
To get an entry, you need to specify the content type UID, locale code, and the UID of the entry.
entry = $client.content_type('content_type_uid')
.entry('entry_uid')
.locale('locale_code')
.fetch
entry = $client.content_type('content_type_uid')
.query
.find