Chloe
Chloe

Reputation: 26294

How do I embed an environment variable into a .coffee file in Rails?

I saw this question, but it didn't work: How to access environment variable from rails on your javascript?

I have this code

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

And I have this environment set

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

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

Yet it is generating this JS:

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

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

Upvotes: 3

Views: 1368

Answers (2)

Chloe
Chloe

Reputation: 26294

No one had an answer for me and I couldn't wait all day so I did it a different way.

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

yields

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

Upvotes: 0

Matouš Bor&#225;k
Matouš Bor&#225;k

Reputation: 15954

In your template, you're missing a = to actually render the output of the ERB expression. The following should work:

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

See the docs for more.

Upvotes: 3

Related Questions