Setup Sidekiq and Redis

If you want Sidekiq to be able to talk to Redis on staging and production servers, you need to add the following to your configuration:

# config/initializers/sidekiq.rb
require 'sidekiq'

Sidekiq.configure_client do |config|
  config.redis = { url: REDIS_URL }
end

Sidekiq.configure_server do |config|
  config.redis = { url: REDIS_URL }
end
# config/initializers/redis.rb
require 'redis'
require_relative '../constants/redis'

Redis.current = Redis.new(url: REDIS_URL)

Now we can determine the correct REDIS_URL like this:

# config/constants/redis.rb
module RedisConstantHelper
  module_function

  def redis_url
    "redis://localhost:#{port}/#{db_number}"
  end

  def db_number
    # Returns a number between 2 and n.
    # Redis db#1 is used for development.

    db_number = 1

    if rails_env == 'test'
      normalized_test_number = [ENV['TEST_ENV_NUMBER'].to_i, 1].max
      db_number += normalized_test_number
    end

    db_number
  end

  def port
    case rails_env
    when 'staging'
      # <staging_port>
    when 'production'
      # <production_port>
    else
      6379 # default Redis port
    end
  end

  def rails_env
    defined?(Rails) ? Rails.env : ENV['RAILS_ENV']
  end
end

REDIS_URL = RedisConstantHelper.redis_url

Make sure to require the /constants folder on startup:

# config/application.rb
module ProjectName
  class Application < Rails::Application
    
    # require /constants on startup
    Dir.glob(Rails.root.join('config/constants/**/*.rb')).each do |filename|
      require filename
    end
    
  end
end
Klaus Weidinger about 1 month ago
This website uses short-lived cookies to improve usability.
Accept or learn more