LoginSignup
2
1

More than 3 years have passed since last update.

rails で Redis の設定を database.yml の様に環境変数から読み込む

Posted at

概要

rails の database.yml では環境変数から設定値を取得し、取得出来なかった場合は、デフォルト値を使う書き方が出来ます。同じ事を Redis の設定ファイルでも行う方法です。
若手から実現したかったけど、やり方が分からずに断念していたと聞いたので、記事に残すことにしました。

環境

Rails 6.0.3

Redis の設定ファイル

設定ファイルは config/redis.yml です。

default: &default
  host: <%= ENV.fetch('SESSION_DB_HOST') { 'session_db' } %>
  port: <%= ENV.fetch('SESSION_DB_PORT') { 6379 } %>

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

host と port を database.yml と同じく、環境変数が存在すれば環境変数から取得しセット、環境変数が存在しない場合はブロックで指定したデフォルト値をセットする様にしています。

Redis の初期化

config/initializers/redis.rb で Redis の初期化を行います。

path = Rails.root + 'config/redis.yml'
yaml = Pathname.new path if path

config =
  if yaml && yaml.exist?
    YAML.load(ERB.new(yaml.read).result)[Rails.env] || {}
  else
    raise "Could not load redis configuration. No such file - #{path}"
  end

Redis.current = ConnectionPool.new(size: 10, timeout: 5) do
  Redis.new(
    host: config['host'],
    port: config['port']
  )
end

YAML.load(ERB.new(yaml.read).result)[Rails.env] の箇所で、読み込んだ redis.yml を ERB クラスを使って、eRuby スクリプトとして処理をしています。

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1