如何在Rails中将环境变量显示为一组

时间:2019-03-26 06:34:42

标签: ruby-on-rails ruby environment-variables

我正在使用Rails 5.2应用程序。我想在端点中将环境变量显示为一组。

env_controller.rb

class EnvController < ApplicationController
  def index
   render json: ENV.to_h
  end
end

加载http://localhost:3000/env时,看到以下结果

{
  "XDG_VTNR": "7",
  "MANPATH": "/home/ubuntu/.nvm/versions/node/v4.6.0/share/man:/home/ubuntu/.rvm/rubies/ruby-2.6.2/share/man:/home/ubuntu/.rvm/man:/usr/lib/jvm/java-8-oracle/man:/usr/local/man:/usr/local/share/man:/usr/share/man",
  "S3_SOURCE_PATH": "dev/source",
  "DB_ENV_USER": "postgres",
  "XDG_SESSION_ID": "c2",
  "rvm_bin_path": "/home/ubuntu/.rvm/bin",
  "S3_DESTINATION_PATH": "dev/destination",
  "SESSION": "ubuntu",
  "DB_PORT_5432_TCP_ADDR": "localhost",
  "S3_REGION": "us-east-1"
}

我想按以下方式对环境变量进行分组。我的预期结果如下

{
  "S3": {
    "S3_SOURCE_PATH": "reports/source",
    "S3_DESTINATION_PATH": "reports/destination",
    "S3_REGION": "us-east-1"
  },
  "DB": {
    "DB_ENV_USER": "postgres",
    "DB_PORT_5432_TCP_ADDR": "localhost"
  },
  "Others": {
    "XDG_VTNR": "7",
    "MANPATH": "/home/ubuntu/.nvm/versions/node/v4.6.0/share/man:/home/ubuntu/.rvm/rubies/ruby-2.6.2/share/man:/home/ubuntu/.rvm/man:/usr/lib/jvm/java-8-oracle/man:/usr/local/man:/usr/local/share/man:/usr/share/man",
    "XDG_SESSION_ID": "c2",
    "rvm_bin_path": "/home/ubuntu/.rvm/bin",
    "SESSION": "ubuntu"
  }
}

我绝对需要将“ S3”和“ DB”进行分组。我的应用程序中还有更多变量应按以下方式分组。以上是示例。

如何显示以上内容?

1 个答案:

答案 0 :(得分:1)

我认为您想要的是自定义序列化程序。与此类似:

class EnvSerializer
  def as_json
    {
      S3: env_select('S3'),
      DB: env_select('DB'),
      Other: env_reject('S3', 'DB')
    }
  end

  private

  def env_select(prefix)
    ENV.select { |k, v| k.start_with?(prefix) }
  end

  def env_reject(*prefixes)
    ENV.reject { |k, v| k.start_with?(*prefixes) }
  end
end

控制器中的外观如下:

class EnvController < ApplicationController
  def index
    render json: EnvSerializer.new.as_json
  end
end