如何将环境变量嵌入到Rails中的.coffee文件中?

时间:2017-05-26 17:34:02

标签: javascript ruby-on-rails coffeescript

我看到了这个问题,但它没有成功: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("");

2 个答案:

答案 0 :(得分:2)

在您的模板中,您错过了=来实际呈现ERB表达式的输出。以下应该有效:

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

有关详情,请参阅the docs

答案 1 :(得分:0)

没有人对我有答案,我不能整天等待,所以我采取了不同的方式。

_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);