1

I have a JavaScript snippet in my Ruby on Rails application that talks to a remote server and passes it a JSON composed of an array of dictionaries containing things like SKU, price, etc.

It's simple to generate in Ruby:

@items = @order.line_items.map do |item|
  {
    sku: item.variant.sku,
    price: item.variant.price
    quantity: item.quantity
    currency: current_user.currency
  }
end

However, when I insert it in JavaScript -- it doesn't work.

{        
  items: "<%= @items %>"
}

The problem I think is that the entities are escaped. If I use alert to inspect the returned value, I can see all the entities like quotation marks are escaped.

Other places where I interpolate values directly seem to work fine. For example:

invoice_number: "<%= @order.id %>"

Others have had this problem, but none of the solutions appear to work in this case. I've tried raw, html_safe, etc.

I must be missing something. What is the best way to solve this problem?

1 Answer 1

1

There are three problems.

First, you don't need "" around <%= @items %>.

Second, <%= @items %> inserts @items.to_s, but {"key" => 12}.to_s equals '{"key"=>12}', which is not a valid JSON.

Third, you need html_safe to make Rails to not escape special characters.

You get:

items: <%= @items.to_json.html_safe %>
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Danil but this doesn't work. JS gives me a syntax error in the console related to a missing close parenthesis. (??) It's frustrating because I can hand code with dummy values and get it to work, but can't get the values to insert from ruby. It really wants to represent those quotes as entities.
items: "[{&quot;sku&quot;=&gt;&quot;1068R-FR&quot;, &quot;price&quot;=&gt;#&lt;BigDecimal:7f8cede8d498,&#39;0.1901E2&#39;,18(27)&gt;, &quot;quantity&quot;=&gt;1, &quot;currency&quot;=&gt;&quot;EUR&quot;}]" }
(That's what the original code puts into the page source). I've tried several different approaches but it always represents quotes as entities. If I hand code, it works great, but of course that won't work irl. There must be a way to get a JSON object out of Ruby and into JS? Thanks Danil for any suggestions!
Hang on...you were right. When I printed out my array onto the rails console, I got this: [{"sku"=>"1068R-FR", "price"=>#<BigDecimal:7f8cf5157af0,'0.1901E2',18(27)>, "quantity"=>1, "currency"=>"EUR"}]. When I hand coded that big decimal to "10" AND used your suggestion, those entity tags went away and I got this in the source: [{"sku":"1068R-FR","price":"10","quantity":1,"currency":"EUR"}]. Yay!
Now the problem is to get the BigDecimal to show up correctly. Any suggestions?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.