我在我的Rails应用程序中使用Google Drive API。 API运行正常。我有以下client_secret.json文件:
{
"type": "service_account",
"project_id": "gobirdie-landing-page",
"private_key_id": "xxxxx",
"private_key": "-----BEGIN PRIVATE KEY----- xxxxx -----END PRIVATE KEY-----\n",
"client_email": "xxxxxxx@gobirdie-landing-page.iam.gserviceaccount.com",
"client_id": "xxxxxxxxx",
"auth_uri": "xxxxxx",
"token_uri": "xxxxxxx": "xxxxxxxx": "xxxxxxxxx"
}
在我的 Controller 中被称为
@session = GoogleDrive::Session.from_service_account_key("client_secret.json")
使用此配置没问题,我设法使用了API。但是,我想将JSON存储在.env文件中,如下所示:
CLIENT_SECRET = "{
"type": "service_account",
"project_id": "gobirdie-landing-page",
"private_key_id": "xxxxx",
"private_key": "-----BEGIN PRIVATE KEY----- xxxxx -----END PRIVATE KEY-----\n",
"client_email": "xxxxxxx@gobirdie-landing-page.iam.gserviceaccount.com",
"client_id": "xxxxxxxxx",
"auth_uri": "xxxxxx",
"token_uri": "xxxxxxx": "xxxxxxxx": "xxxxxxxxx"
}"
并以这种方式在 Controller 中调用它
@session = GoogleDrive::Session.from_service_account_key(ENV['CLIENT_SECRET'])
或以这种方式
@session = GoogleDrive::Session.from_service_account_key(JSON.parse(ENV['CLIENT_SECRET']))
但是两种方法都行不通。所以我的问题是:“是否可以将JSON文件存储在ENV变量中?”
最佳答案
将JSON对象转换为字符串并将其存储在ENV中
您可以使用JSON.dump
将JSON对象转换为字符串
然后在您的 Controller 中JSON.parse(ENV['CLIENT_SECRET'])
或者
您可以在google_session.rb
文件夹中创建一个initializers
$google_session = GoogleDrive::Session.from_service_account_key(
# config goes here
)
在您的 Controller 中,您将可以访问
$google_session
全局变量
关于ruby-on-rails - 是否可以使用dotenv将JSON文件存储到ENV变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56277661/