Caching Example

  • how-to
    +
    A walk-through of the steps to use Couchbase as a caching layer for Rails.

    This example demonstrates how to integrate Couchbase into a caching layer of the Rails web-framework.

    You can also find the full code for this example here.

    Configuration

    All necessary classes that implement rails caching API are part of the official SDK for Ruby, so to add it to the application you just need to update your Gemfile:

    gem "couchbase"

    Do not forget to run bundle install to ensure that all dependencies have been satisfied.

    Now the application have to be configured to use Couchbase as a caching backend. Corresponding configuration usually kept in the configuration environment file and looks like this:

        config.cache_store = :couchbase_store, {
          connection_string: ENV.fetch("COUCHBASE_CONNECTION_STRING", "couchbase://localhost"),
          username: ENV.fetch("COUCHBASE_USERNAME", "Administrator"),
          password: ENV.fetch("COUCHBASE_PASSWORD", "password"),
          bucket: ENV.fetch("COUCHBASE_BUCKET", "default"),
          scope: ENV.fetch("COUCHBASE_SCOPE", "_default"),
          collection: ENV.fetch("COUCHBASE_COLLECTION", "_default")
        }

    In this development example, we will try to discover cluster location and credentials in the environment variables, with a fallback to localhost and safe default. In a production environment all sensitive information (like passwords) must be managed in secure ways, using secrets providers.

    Usage

    With the configuration step, all Couchbase-specific code is done — after that familiar API of the Rails.cache will be used. In this example, we cache the current time for the 3 seconds:

    class WallClockController < ApplicationController
      def now
        @current_time = Rails.cache.fetch("current_time", expires_in: 3.seconds) do
          Time.now
        end
      end

    Additional Resources