How to deal with HTML entities in Rails to_json output? - javascript

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

Related

javascript syntax for parameters in the context of rails 6 packs

Action: a javascript action attempting to retrieve data based on two parameters, a user-input one and an issuing page parameter.
whereas in the past something like the following would work:
<%= javascript_tag do %> chart.data = data_<%=j params[:nation_id] %>; <% end %>
now with the javascript being 'packed', the compilation of syntax like <%=j params[:nation_id] %> does not work and returns :
/search.json?nation_id=%22%3C%=j%20params[:nation_id]%20%%3E%22&q=mi
modifying the packs/muni.js file as follows, also does not generate a proper url for the search function
var options = {
url: function(phrase) {
return '/search.json?nation_id="#{params[:nation_id]}"&q=' + phrase;
},
getValue: "name",
};
returning
/search.json?nation_id=%22
the page is set with /new?top%5Bnation_id%5D=1&commit=Set
How does the javascript pack need to be written?
Javascript pack is not rendered for each request/visitor - whole point is that it is packed once per deploy and is the same for all (except for when you have several packs, dynamic module loading and other advanced techniques, but still code is not changed per request). In fact, older method with asset pipeline is very similar in this aspect.
Do not try using ruby inside the pack, but instead think of a way to pass the parameter to the js code.
For example, you can pass it via a adding some html tag an querying it from javascript:
In view:
<meta name="nation_id" content="<%= params[:nation_id] %>" />
in js:
nation_id = document.querySelector('meta[name="nation_id"]').content;
return `/search.json?nation_id=${nation_id}&q=${phrase}`;
PS. also you might need to escape your phrase with encodeURIComponent

How to run a javascript string from database in html with rails

i have a this string:
#html = "HELLO <script> alert("this code is from database")</script>"
in my file view .erb:
but dont work
is possible run this code with rails from string?
Bad practice, but it is possible
1 with html_safe
<%- #html.html_safe %>
2 with raw if your variable could be nil
raw(#html)

Use Ruby on Rails in Javascript script

I try to create my own SonarQube Widget and I have the following question ?
I want to save in a javascript variable the result of my Metrics. The problem is that I don't succeed to use Ruby on Rails with Javascript.
<script type="text/javascript">
var text = "<%= format_measure('sonar.metric.arcadsoftware.rpg.ruleset1') %>";
alert(text);
</script>
If I use just <p><%= format_measure('sonar.metric.arcadsoftware.rpg.ruleset1') -%> </p> the result is "True" on my widget.
So I want to store the String 'True' in my javascript variable text.
Thank you

Converting JS to CoffeScript, missing operand?

I've got a HighCharts javascript that i'm trying to convert to CoffeeScript, using some online converters.
However all of them error out with "missing operand"
Here's the code
$(function() {
$('#container').highcharts({
series: [{
name: "<%= x %>'",
data: [
<% #sprice = #price * #quantity %>
<% 0.upto(#years).each do |stack| %>
<%= number_with_precision(#sprice, precision: 2) %>,
<% #sprice = ((#sprice*percentage)/100)+#sprice %>,
<% end %>]
}]
});
});
Where's the missing operand tho? Does it have something to do with embedded ruby inside my JS script?
Script is working as intended inside HTML view file. But i'm trying to move it into controller's js file to clean it up abit. Controller's js file is in coffescript by default, so that's where im kind of stuck.
Any help appreciated, thanks!
As noted above:
If #years is small
then ERB a couple simple scalars and then build the array in CoffeeScript;
If #years is large
then do the heavy lifting in your controller and stuff the data into your CoffeeScript as a one line JSON blob.
Or AJAX it or split the data out into a separate piece of JavaScript and leave the code as CoffeeScript.
References
CoffeeScript, TypeScript? How about JavaScript

Access Rails global constant in Javascript / jQuery

My setup: Rails 3.0.9, Ruby 1.9.2, jQuery 1.6.2
Rails
constants.rb (initializer file)
DEFAULT_REPLY = "Add a reply..."
Rails
index.html.erb
<%= javascript_include_tag 'reply' %>
...(rest of view code)...
reply.js
$(function() {
var default_reply = <%= h DEFAULT_REPLY -%>;
...(rest of jQuery code)...
});
This throws an error Uncaught SyntaxError:Unexpected token %=, I tried to enclose it in quotes like var default_reply = '<%= h DEFAULT_REPLY -%>' and it output the value as is, meaning default_value has the value of <%= h DEFAULT_REPLY -%>' which is clearly not what I intended. What am I doing wrong?
EDIT
Given the feedback, I have reconsidered and is now using a local variable and jQuery to pull the value from the textarea upon page load.
You need to add .erb to the end of your .js file, along with add the quotes around the string.
The name of your javascript file should be reply.js.erb.
Currently, your .js file is not being run through rails, and is being served statically. That is why when you put the quotes around the string, it output the string '<%= h DEFAULT_REPLY %>' instead of the correct text.
I'd strongly recommend against this approach but I think you're confusing two things here.
Assuming reply.js is in public/javascripts/reply.js, this is a static JS file that is served up by your server. You cannot put any dynamic ("server side") code in here as the file is not evaluated in any manner, just passed back statically.
If you want a global JS variable to use in your files, you'd need to do assign it in your layout file app/views/layouts/application.html.erb or in your action files (index.html.erb, show.html.erb, etc).
Any ERB file is evaluated before returning it, so you could put
<script type='text/javascript'>
$(function() {
var default_reply = "<%= escape_javascript DEFAULT_REPLY %>";
});
</script>
above the <%= yield %> statement of your layout file.
Again, I'd STRONGLY recommend against this approach but if that's why you need, I think this will solve it.
It sounds like you named your view template incorrectly, does it end in .html.erb? If not, it won't evaluate the ERB fragment you pasted.
Once you fix that, you can embed what you want with the following ERB code:
$(function() {
var default_reply = "<%= h DEFAULT_REPLY -%>";
...
});
If it is a rails 3 App why are you using that syntax? try:
var default_reply = <%= DEFAULT_REPLY %>;

Categories