2017-05-26 125 views
0

我看到了这个问题,但没有奏效:How to access environment variable from rails on your javascript?如何在Rails中将环境变量嵌入到.coffee文件中?

我有这样的代码

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(""); 

回答

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); 
+0

根据时间戳,你只需等待23分钟就可以发布你的问题和这个答案... – BoraMa

+1

时间就是金钱... – Chloe

2

的In y我们的模板,您错过了=实际呈现ERB表达式的输出。以下应该工作:

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

请参阅the docs了解更多。

+0

哦......我一般只使用HAML。哎呀。 – Chloe

+0

哦,不幸的是,这不适用于带预编译资源的Heroku。显然,当它预编译Javascript时,它不包含通过'heroku config'设置的环境变量。 – Chloe