Rubyのライブラリやアプリケーションで使えるENVの一覧を取得する方法

最近、コンテナ化や The Twelve-Factor App環境変数を使う機会が多くなってきたので、一覧を作る方法が欲しくなった。

gemにする気力は今無いので、とりあえずコード片をブログに書いておく。*1

# config/application.rb の最後に以下のコードを貼ったら、それっぽく動いた。

module EnvLogger
  def self.histories
    @histories ||= []
  end

  def [](key)
    EnvLogger.histories << key
    super
  end

  def fetch(key, default = nil)
    EnvLogger.histories << key
    super
  end
end
ENV.singleton_class.prepend EnvLogger

at_exit do
  EnvLogger.histories.uniq.sort.each { |key| puts key }
end

Special thanks

ruby-jp で聞いたら、 @p_ck_ さんが即レスしてくれた。はやい。

f:id:sinsoku:20190826204921p:plain
ruby-jp

*1:将来、気が向いたらgem化するかも?やる気ある人いたら誰か代わりに頼む