Rails + JS - Using instance variable (array of arrays with strings) - javascript

I have the following in a html.erb file:
<%= #location_list = [['test',2]] %>
<script type="text/javascript">
var test = <%= #location_list.to_json %>
alert(test);
</script>
And the alert is not showing up.
However if I do <%= #location_list = [[3,2]] %> - The alert is showing up.
Why?

<%= %> tag means output something. In your case, you probably dont want to output anything, so I guess you are looking for
<% #location_list = [['test',2]] %>, which means normal statement no output will be involved
Sorry, havn't really answer your question.
var test = <%= #location_list.to_json %>
should be
var test = "<%=j #location_list.to_json %>"

Related

Using RegExp and eval() to replace a value

I need to use RegExp to replace a string and eval() to execute the object.
In my code below, I'm currently in a forEach of items.
item.url : http://localhost:3000/formation/[[item.id]]/[[item.launch_url]]
My code :
<% _.forEach(items, function(item) { %>
<% _.forEach(tableLineActions, function(tableLineAction) { %>
<% if (tableLineAction.conditionToShow) { %>
<% var label = tableLineAction.label; %>
<% var url = tableLineAction.url.replace(/\[\[item.id\]\]/g, item.id).replace('[[modelName]]', modelName).replace('[[item.seo_url]]', item.seo_url); %> // not reusable code
<% url = eval(url.replace(/\[\[/g, '').replace(/\]\]/g, '')); %> // test of a reusable code
<li><icon class="material-icons"><%=tableLineAction.icon%></icon><%=label%></li>
<% } %>
<% }); %>
<% }); %>
Error message : Invalid regular expression flags
I found a solution but this one is not maintenable if I want to send severals properties :
url = url.replace(/\[\[item.id\]\]/g, item.id).replace(/\[\[item.launch_url\]\]/g, item.launch_url)
With this solution, I need to add a new replace() method when a new property is sending and I want something more reusable without specifying all properties to replace.

Stop javascript from implicitly converting string to int

So I have a datapoint object with fields date(string) and count(integer). I'm trying to add them to arrays with some JS inside of my show view. Everything is working well - except that my date string is being converted to a series of JS arithmetic. For example: a value of "2015-05-05" is getting converted to 2005. Code follows:
<h1 id="chart"></h1>
<script language="javascript" type="text/javascript">
var counts = ['Count']
var dates = ['x']
<% #chart.datasource.datapoints.each do |c| %>
dates.push( <%= c.date %> )
counts.push( <%= c.count %> )
<% end %>
chart(counts, dates);
</script>
You're missing quotes:
var counts = ['Count']
var dates = ['x']
<% #chart.datasource.datapoints.each do |c| %>
dates.push( "<%= c.date %>" )
counts.push( <%= c.count %> )
<% end %>
chart(counts, dates);
Wrapping the value in quotes will force JS to consider it as a string primitive, rather than a number and arithmetic operators.

Javascript map from java map

I want to create a javascript map from a java map to set a dropdown value depending upon the value selected in another dropdown.
Below is the code(not working):
var categoryAndReportsMap = new Object();
<%
Map<String,Set<String>> categoryAndReportsJ = (Map<String,Set<String>>) request.getAttribute("categoryAndReports");
for(Map.Entry<String,Set<String>> e : categoryAndReportsJ.entrySet()){ %>
categoryAndReportsMap[ <% e.getKey(); %> ] = <% e.getValue(); %>;
<% } %>
Please suggest how can I achieve this.
You need quotes around the keys and values :
categoryAndReportsMap["<%= e.getKey() %>"] = "<%= e.getValue() %>";
But this supposes those strings don't contain quotes themselves. The best solution would be to use a JSON serializer like the excellent gson, this would be as simple as
var categoryAndReportsMap = <%= gson.toJson(categoryAndReportsJ) %>;

javascript in my .html.erb using embedded ruby--escaping problems

I'm trying to embed data I have defined in my controller in my view.
in view.html.erb:
<script>
some_var = <%= #var_data %>
some_ints = <%= #int_data %>
</script>
in my controller:
#var_data = ['hi', 'bye']
#int_data = [1,2,3,4]
however, when I view the generated html file, it looks like
<script>
some_var = ["hi", "bye"]
some_ints = [1,2,3,4]
</script>
ie the ints are fine but all the quotes got escaped. I tried
some_var = <%= #var_data.map {|i| i.html_safe} %>
instead but it didn't do anything (and also html_safe didn't work on the whole array). How should I do this?
Thanks
have you tried this?
<%=raw #var_data %>

How can I return javascript from a Ruby on Rails helper method?

I have a Note model, which can contain have either an image link attachment (linktype = "image" or some text (linktype = "text). When I display the notes, the method of display changes depending on the linktype. An example is:
<% #notes.each do |q| %>
<h2 class="title"><%= q.name %></h2>
<% if q.linktype == "other"%>
<script type="text/javascript">some javascript</script>
<% elsif q.linktype == "text"%>
<%= q.text %>
<% elsif q.linktype == "image"%>
<img src="<%= q.link %>" />
<% end %>
<% end %>
I have to display the notes in a few different views in my site, so rather than have to repeat the viewing code multiple times, I want to have it in one place and refer to it from different views.
My initial thought was to put the display code in a helper, something like this:
<% #notes.each do |q| %>
note_display(q.linktype, q.link)
<% end %>
But some of the displaying involves javascript (line 4 in first code block). Can I still use a helper method, even though I would need it to return javascript? If so, how do I do it? Thanks for reading.
There's nothing special about javascript, you can return it from helpers as you would return other html content. The only thing I would suggest is to use helpers for tags like
image_tag(q.link)
javascript_tag("some javascript")
content_tag("h2", q.name, :class => "title")
As far as ERB is concerned, JavaScript is just string content like anything else rendered by a template. So your helper method can just construct and return a string:
def note_display(note)
content = ''
content << content_tag('h2', h(note.name), :class => 'title')
if note.linktype == 'other'
content << javascript_tag("some javascript")
elsif note.linktype == 'text'
content << h(note.text)
elsif note.linktype == 'image'
content << image_tag(note.link)
end
content
end
You can use this helper method using:
<% #notes.each do |n| %>
<%= note_display(n) %>
<% end %>

Categories