Ruby json gem is encoding html entities - javascript

I make a hash called timeOffsets in my code
#timeOffsets = Hash.new
total=0
#sections.each do |i|
#timeOffsets[i.shortcode] = total
total+=i.length
end
And I render it in Javascript using to_json, :
timeOffsets=<%=#timeOffsets.to_json%>;
but I get it with the HTML entities encoded:
timeOffsets={"Introduction_to_Lists":0,"Removing_elements":693,"Joining__join_":1490};
How do I stop it from encoding the HTML entities?

timeOffsets=<%=raw #timeOffsets.to_json%>
Use the raw view helper.

Related

How do I render a hash in a view where the key comes from the page itself?

More detailed question: How do I render a hash in a view, where the hash is passed from the controller but the key comes from the page via Javascript?
I know I can do something like this <%= hash["key"] %>, but in my case "key" is coming from another hash element generated on my page with JS, call it js_hash.js_key.
I've tried the following to no avail
<%= raw hash %>[js_hash.js_key]
<%= raw hash %>[js_hash["js_key"]]
The following worked (single quotes were important):
var some_js_var = JSON.parse('<%= the_hash.to_json.html_safe %>');
console.log(some_js_var[js_hash.js_key]);

How do I prevent Rails form escaping my apostraphes in my view?

I’m using Rails 4.2.3. In my view, I want to output some JS, so I have this
<%
puts "size: #{#user_my_objects.size}"
js_data = []
#user_my_objects.each do |user_my_object|
my_object_day_fmted = user_my_object.my_object.day.strftime("%Y/%m/%d")
js_data.push( "[new Date('#{my_object_day_fmted}')).getTime(), #{user_my_object.time_in_ms}]" )
end
%>
var data = [<%= js_data.join(",") %>];
but Rails keeps converting my apostrophes to “'” characters and its causing “Uncaught SyntaxError: Unexpected token &” JS errors when the page renders. Here is an example of how the output looks
var data = [[new Date('2011/10/23')).getTime(), 1286000],[new Date('2013/08/11')).getTime(), 2779000],[new Date('2013/10/26')).getTime(), 1288000],[new Date('2014/06/28')).getTime(), 2915000],[new Date('2014/09/07')).getTime(), 6256000],[new Date('2015/07/25')).getTime(), 2788000],[new Date('2015/08/22')).getTime(), 1488000]];
How do I prevent Rails from applying HTML escaping to characters for this page only?
try this one instead
<%= raw %>

Why is my embedded ruby json string encoded with html entities when parsed in the view?

I've created a rails action that makes a GET request to a service and then passes the response to the view as #job_data. The code works fine in retrieving the response, and I've verified the json object looks correct.
def show
#url = URI.parse(##jobs_base_url + "/" + params[:id] + "?TestMode=true")
req = Net::HTTP::Get.new(#url.to_s)
res = Net::HTTP.start(#url.host, #url.port) {|http|
http.request(req)
}
#job_data = HTMLEntities.new.decode res.body
end
However, I'm trying to do a little javascript to manipulate DOM elements using this json object. I'm trying to insert the script into the html to do something very basic with the json object, but can't seem to get it to pass correctly:
<script type="text/javascript" charset="utf-8">
$(function() {
var $data = <%= #job_data %>;
$('#jobtable').append($data.Id);
When I debug the page I see that all the entities in the string are encoded (e.g. &quot instead of quotation marks). I've tried to de-entityify the string with HTMLEntities as in the code above for the action, but it has no effect and is the same as if I had left the #job_data set to:
#job_data = res.body
Can anyone explain where the encoding happens and how I can resolve this? Is the problem with the action or with the javascript in the view? What's the preferred way to pass a json string/object from a response in an action to javascript in the view?
Already answered here:
Ruby json gem is encoding html entities
The trick is to use raw in the view's embedded ruby to avoid the encoding:
var $data = <%= raw #job_data %>;

Render ERB with underscore templates without displaying in browser

Am trying to generate a PDF from a HTML file which itself is generated from dynamic content. So there is a controller action "generate_pdf" which takes HTML content and renders a PDF. The pdf generation bit works fine. Generating the HTML is where I am stuck.
#reports_controller.rb
def generate_pdf
#report = Report.where(:id => params[:id])
html_content = render_to_string(:layout => false)
#Use the html_content to generate PDF
end
Now the erb file is as follows :
#views/reports/generate_pdf.html.erb
This is the generated pdf from erb.
The following is a generated content. The report's id is <%= #report.id %>
and the name is "<%= #report.name %>". </br>
It has <%= #report.items %> items.
This erb without any underscore templates works great and render_to_string generates correct HTML content.
But now if I use underscore.js templates ( the same report is also displayed in browser and the application uses Backbone.js and Underscore.js a lot) to generate the content of the report then render_to_string returns incorrect HTML. By incorrect, I mean, the output is the underscore.js template code itself and not the actual content.
{{ _.each(items, function(item) { }}
...
There is no JavaScript environment available inside render_to_string that would render the underscore.js templates. How can I handle this situation? Since most of our templates are in underscore.js, we thought it would make sense to reuse as much as of it as possible instead of creating a different template (in ERB ) just for PDF.

How to deal with HTML entities in Rails to_json output?

I'm writing an app that uses Rails on the backend and javascript/backbone on the frontend. I'm trying to bootstrap some rails models into my javascript. Specifically, I'd like to load the contents of #courses into a js variable called window.courses. I've got the following in an html.erb file.
<%= javascript_tag do %>
window.courses = JSON.parse('<%= #courses.to_json %>');
<% end %>
I'm expecting the erb preprocessor to render this into valid javascript, like so
<script type="text/javascript">
//<![CDATA[
window.courses = JSON.parse('[{"code":"myCourseCode", ...
//]]>
</script>
... but, instead, I'm getting code that includes HTML entities.
<script type="text/javascript">
//<![CDATA[
window.courses = JSON.parse('[{"code":"myCourseCode", ...
//]]>
</script>
Obviously, I get javascript errors when I try to parse this.
Does anyone know how I can deal with these HTML entities in order to produce valid javascript? I realize that one option would be to unescape the entities on the client side, but this seems like a roundabout solution. Is there a way that I can get Rails to produce JSON that doesn't need unescaping?
If you intend to use raw(obj.to_json) you MUST ensure the following is set.
ActiveSupport.escape_html_entities_in_json = true
The question is solved by my comment, just for the record:
Rails escapes strings that are printed using <%= 'string' %>. By this, it is save to ouput user data.
So, if you don't want Rails to escape the output, you have to tell Rails explicitly by using raw('string').
In your code, that would be:
<%= raw(#courses.to_json) %>

Categories