简体   繁体   中英

Creating a multi-line string in javascript that accepts ruby object

So I am trying to get my code to match Stripe's js example:

var stripe = Stripe('pk_test_REST_OF_MY_KEY');

Here are the lines from my .js.erb file that call the right key from my secrets.yml file. When this renders I get the following error in the browser console Uncaught ReferenceError: pk_test_REST_OF_MY_KEY is not defined

  var stripe = Stripe(
    <% if Rails.env == 'production' %>
      <%= Rails.application.secrets.stripe(['publishable_key']).second[1].to_s %>
    <% else %>
      <%= Rails.application.secrets.stripe(['publishable_key']).first[1].to_s %>
    <% end %>
  );

I've tried

... Stripe(` 
  RUBY LINES BETWEEN BACKTICKS 
`);

... Stripe(' + 
  RUBY LINES BETWEEN PLUSES 
+ ');

So it has to be some finicky js syntax with the (' '); not accepting the ruby value as a string, right? We know the ruby is running because the console error is printing the right value.

Also, the ruby is correct because it produces Rails.application.secrets.stripe(['publishable_key']).first[1].to_s => "pk_test_REST_OF_MY_KEY" in the console

I think i should just be:

var stripe = Stripe(
  <% if Rails.env == 'production' %>
    '<%= Rails.application.secrets.stripe(['publishable_key']).second[1].to_s %>'
  <% else %>
    '<%= Rails.application.secrets.stripe(['publishable_key']).first[1].to_s %>'
  <% end %>
);

First of all, it will be helpful to clean up your code a bit to see what's happening where. Move the logic up to the top of the file:

<%
  config = Rails.application.secrets.stripe(['publishable_key'])
  stripe_key = Rails.env.production? ? config.first[1] : config.second[1]
%>

...or, better, yet, a helper:

def stripe_key
  config = Rails.application.secrets.stripe(['publishable_key'])
  Rails.env.production? ? config.first[1] : config.second[1]
end

Then, in your JavaScript:

var stripe = Stripe('<%= j(stripe_key) %>');

// ...or...

var stripe = Stripe(<%= stripe_key.to_json %>);

Be careful to note the presence or absence of single-quotes in both cases. The j helper will escape special characters (including quotes and newlines) inside the string, but the returned string won't be wrapped in quotation marks, whereas to_json will return a string already wrapped with double-quotes.

PS When you say this:

Rails.application.secrets.stripe(['publishable_key'])

...are you sure you don't mean:

Rails.application.secrets.stripe['publishable_key']

# ...or...

Rails.application.secrets.stripe.publishable_key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM