【问题标题】:How do I embed an environment variable into a .coffee file in Rails?如何将环境变量嵌入到 Rails 中的 .coffee 文件中?
【发布时间】:2017-05-26 17:34:01
【问题描述】:

我看到了这个问题,但是没有用:How to access environment variable from rails on your javascript?

我有这个代码

subscriptions.coffee.erb
$ ->
  # Create a Stripe client
  stripe = Stripe( "<% ENV['STRIPE_PUBLIC'] %>" )

我已经设置了这个环境

C:\Users\Chloe\workspace\>echo %STRIPE_PUBLIC%
pk_test_7aMtxxxxxxxxxxxxx4p3M

C:\Users\Chloe\workspace\>rails server --bind 0.0.0.0
=> Booting Puma

然而它正在生成这个 JS:

http://localhost:3000/assets/subscriptions.self-dfceb50c7f2eec8201fd3f59a7660a6763333b1e27f564e812f93c8ce9019188.js?body=1

(function() {
  $(function() {
    var card, elements, form, stripe, stripeTokenHandler, style;
    stripe = Stripe("");

【问题讨论】:

  • 对于其他登陆这里的人,我可以在.js.coffee 文件中使用&lt;%= ENV[ "MY_VAR" ] %&gt;,只需在文件名中添加.erb,例如.js.coffee.erb。请记住,这是在预编译资产时在“ERB”中处理的,这通常在服务器上部署后立即发生,因此它非常受限于您可以访问的内容。我也没有在生产中测试这个,只是在开发中,所以一定要再次测试。

标签: javascript ruby-on-rails coffeescript


【解决方案1】:

在您的模板中,您缺少一个 = 来实际呈现 ERB 表达式的输出。以下应该有效:

stripe = Stripe("<%= ENV['STRIPE_PUBLIC'] %>")

请参阅the docs 了解更多信息。

【讨论】:

  • 哦...我一般只使用 HAML。哎呀。
  • 哦,不幸的是,这不适用于带有预编译资产的 Heroku。显然,当它预编译 Javascript 时,它不包含通过 heroku config 设置的环境变量。
【解决方案2】:

没有人给我答案,我等不了一整天,所以我换了一种方式。

_form.haml
=javascript_include_tag 'https://js.stripe.com/v3/'
:javascript
  window.stripe_public = "#{ENV['STRIPE_PUBLIC']}";
subscriptions.coffee
$ ->
  # Create a Stripe client
  stripe = Stripe( window.stripe_public )

产量

view-source:http://localhost:3000/users/1/subscriptions/new
  <script src="https://js.stripe.com/v3/"></script>
  <script>
    window.stripe_public = "pk_test_7xxxxxxxxxxxx4p3M";
  </script>
http://localhost:3000/assets/subscriptions.self-dfceb50c7f2eec8201fd3f59a7660a6763333b1e27f564e812f93c8ce9019188.js?body=1
(function() {
  $(function() {
    var card, elements, form, stripe, stripeTokenHandler, style;
    stripe = Stripe(window.stripe_public);

【讨论】:

  • 根据时间戳,您在发布问题和获得此答案之间仅等待了 23 分钟...
猜你喜欢
  • 1970-01-01
  • 2011-09-11
  • 2019-11-08
  • 2016-08-25
  • 1970-01-01
  • 2020-08-20
  • 2021-11-03
  • 1970-01-01
  • 2020-05-04
相关资源
最近更新 更多