Best way to generate javascript code in ruby (RoR) - javascript

I have seen some rails plugins which generate javascript code dynamically using ruby.
1.
%Q ( mixed block of javascript and ruby )
2.
<<-CODE
some mixed ruby and javascript code
CODE
Being a java developer I don't understand
what those strange looking syntax mean ?
Is one way better than the other ?
can anyone point me to proper documentation about such things ?

The first syntax is Ruby's string literal syntax. Specifically, the %Q (capital Q as opposed to lower-case) means that the string will be interpolated. eg:
%Q[Here's a string with #{a_variable} interpolated!]
Note that you can use any arbitrary characters as the open and close delimiters.
The second syntax is Ruby's heredoc syntax. The dash after the opening << indicates that Ruby will strip whitespace from the beginning of input lines contained in the heredoc block.
Ruby on Rails ships with the Prototype JavaScript framework built-in already. It also ships with JS generator helper methods which generate the Prototype code dynamically based on Ruby code.
You needn't use these if you don't want to. In fact, I rarely use them or Prototype at all, as jQuery is my JS framework of choice. So one way is not "better" than the other (except in the general sense that heredoc is better than the string literal syntax for certain cases).

In Ruby %Q provides a double quote delimited string, so:
%Q(mixed block of javascript and ruby) #=> "mixed block of javascript and ruby"
<<-CODE is what Ruby calls a Here Document, or simply heredoc. This is a mechanism for creating free format strings whilst preserving special characters such as new lines and tabs.
A heredoc is created by preceding the text with << followed by the delimiter string you wish to use to mark the end of the text.
text = <<-DOC
To be, or not to be: that is the question
William Shakespeare
DOC
When this string is printed it appears exactly as it was entered, together with all the new lines and tabs:
To be, or not to be: that is the question
William Shakespeare

%Q is the equivalent to a "" string in Ruby. But if you use such %Q-syntax, you don't need to escape double quotes.
It's a HEREDOC declaration. You also don't need to escape quotes there.
Strings in Ruby.

Here you can find the details.
Ruby with javascript

Related

What quotes can I use while coding? [duplicate]

Working on node.js (server side), I wonder if I should use all back-ticks (`) instead of the regular quotes (" or ') all the time since it will make the code consistent. Is there any specific reason for keeping different type of quotes for different things. Will it affect performance if all non-substitution quotes are converted to back-ticks?
the back-tick allows you to use string templating for example:
var value = 4;
var str = `text with a ${value}`
// str will be : 'text with a 4'
for " vs ' I say look at this post: https://stackoverflow.com/a/9959952/6739517
As for performance, it seems like it would be the same if you are just using back-ticks for plain strings. However when building strings it looks like concatenation is still the way to go. Take a look here:
2018 update: It seems that ES6 string templating can be faster than concatenation in some cases. Take a look at the following post for some hard numbers:
Are ES6 template literals faster than string concatenation?
2020 update: Generally speaking you should not be worried about performance when considering which type of quotation to use. There might be tiny differences but as many have pointed out these are such tiny improvements you are likely better off optimizing your code rather than considering which character to use. That said, this doesn't really answer the question of consistency. For me, I generally follow Airbnb's style guide. That is strings are always declared with single quotes (') unless you need to build a string then you should avoid concatenation and only use string templating with backticks (`). Finally, double quotes are reserved for JSON and HTML.
The performance difference between creating strings using backticks or single quotes would be so absurdly small that I don't think you should consider it as a reason to use one or the other. Here is some basic evidence of that.
However - I would argue against using template string for strings that are not templates simply because it's clear when you use single quotes that no templating is going to occur. If I saw a string with backticks - I would immediately start hunting to see what was going to be substituted, or why they were used. By contrast, single quotes are very clear.
I don't think it will affect performance - but I don't think you should do it "just to be consistent" either. It's not consistent because it's a completely different construct - the same as a while or for loop. They are different tools for different jobs.
Back ticks(``) are called template literals. They are part of ES6.
Difference is:
var name = "world";
var greetES5 = 'Hello '+name;//using single quote
var greetES6 = `Hello ${name}`;//using ticks
You can refer MDN here for more info.

Back-tick vs single quote in js

Working on node.js (server side), I wonder if I should use all back-ticks (`) instead of the regular quotes (" or ') all the time since it will make the code consistent. Is there any specific reason for keeping different type of quotes for different things. Will it affect performance if all non-substitution quotes are converted to back-ticks?
the back-tick allows you to use string templating for example:
var value = 4;
var str = `text with a ${value}`
// str will be : 'text with a 4'
for " vs ' I say look at this post: https://stackoverflow.com/a/9959952/6739517
As for performance, it seems like it would be the same if you are just using back-ticks for plain strings. However when building strings it looks like concatenation is still the way to go. Take a look here:
2018 update: It seems that ES6 string templating can be faster than concatenation in some cases. Take a look at the following post for some hard numbers:
Are ES6 template literals faster than string concatenation?
2020 update: Generally speaking you should not be worried about performance when considering which type of quotation to use. There might be tiny differences but as many have pointed out these are such tiny improvements you are likely better off optimizing your code rather than considering which character to use. That said, this doesn't really answer the question of consistency. For me, I generally follow Airbnb's style guide. That is strings are always declared with single quotes (') unless you need to build a string then you should avoid concatenation and only use string templating with backticks (`). Finally, double quotes are reserved for JSON and HTML.
The performance difference between creating strings using backticks or single quotes would be so absurdly small that I don't think you should consider it as a reason to use one or the other. Here is some basic evidence of that.
However - I would argue against using template string for strings that are not templates simply because it's clear when you use single quotes that no templating is going to occur. If I saw a string with backticks - I would immediately start hunting to see what was going to be substituted, or why they were used. By contrast, single quotes are very clear.
I don't think it will affect performance - but I don't think you should do it "just to be consistent" either. It's not consistent because it's a completely different construct - the same as a while or for loop. They are different tools for different jobs.
Back ticks(``) are called template literals. They are part of ES6.
Difference is:
var name = "world";
var greetES5 = 'Hello '+name;//using single quote
var greetES6 = `Hello ${name}`;//using ticks
You can refer MDN here for more info.

Are there drawbacks to using backticks for all string operations in Typescript? [duplicate]

Is there a reason (performance or other) not to use backtick template literal syntax for all strings in a javascript source file? If so, what?
Should I prefer this:
var str1 = 'this is a string';
over this?
var str2 = `this is another string`;
Code-wise, there is no specific disadvantage. JS engines are smart enough to not have performance differences between a string literal and a template literal without variables.
In fact, I might even argue that it is good to always use template literals:
You can already use single quotes or double quotes to make strings. Choosing which one is largely arbitrary, and you just stick with one. However, it is encouraged to use the other quote if your string contains your chosen string marker, i.e. if you chose ', you would still do "don't argue" instead of 'don\'t argue'. However, backticks are very rare in normal language and strings, so you would actually more rarely have to either use another string literal syntax or use escape codes, which is good.
For example, you'd be forced to use escape sequences to have the string she said: "Don't do this!" with either double or single quotes, but you wouldn't have to when using backticks.
You don't have to convert if you want to use a variable in the string in the future.
However, those are very weak advantages. But still more than none, so I would mainly use template literals.
A real but in my opinion ignorable objection is the one of having to support environments where string literals are not supported. If you have those, you would know and wouldn't be asking this question.
The most significant reason not to use them is that ES6 is not supported in all environments.
Of course that might not affect you at all, but still: YAGNI. Don't use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single quotes in JavaScript? carry over as well. As always, keep your code base consistent and use only one string literal style where you don't need a special one.
Always use template literals. In this case YAGNI is not correct. You absolutely will need it. At some point, you will have add a variable or new line to your string, at which point you will either need to change single quotes to backticks, or use the dreaded '+'.
Be careful when the values are for external use. We work with Tealium for marketing analysis, and it currently does not support ES6 template literals. Event data containing template literals aka string templates will cause the Tealium script to error.
I'm fairly convinced by other answers that there's no serious downside to using them exclusively, but one additional counterpoint is that template strings are also used in advanced "tagged template" syntax, and as illustrated in this Reddit comment, if you try to rely exclusively on JavaScript's automatic semicolon insertion or just forget to include a semicolon, you can run into parsing issues with statements that begin with a template string.
// OK (single (or double) quotes)
logger = console.log
'123'.split('').forEach(logger)
// OK (semicolon)
logger = console.log;
`123`.split('').forEach(logger)
// Not OK
logger = console.log
`123`.split('').forEach(logger) // Error

Various JS templates; Why two {?

I'm puzzled by this notation that did spread a lot after the first templating engine using it became successful. The notation is {{bla}}
Does anyone know the practical reason for having two sets of {}? I think it reads very poorly; The deprecated JQuery one made more sense ( ${bla} )
It's because it's not an often used combination of characters.
Template parsing is all about regular expressions and then turning the text into tokens, and then compiling those tokens into another language (like HTML).
Since we don't want to catch common characters in our regular expressions, we need to use those that aren't common combos of characters.
it's the same reason PHP uses <?php ?> and ASP uses <% %>.
Like in Twig, the lexer looks for {{ }} and {% %} to find Twig commands. If I had to use { }, every time I had that anywhere in the template (not just HTML markup), I'd have to escape it. And since the point of a template language is ease of use, The language needs to make its "tokens" as distinguishable as possible.
How come Distal works without needing any escape characters like {{}}? http://code.google.com/p/distal

Escape dynamic strings in JavaScript

I'm writing a script for a signature function in a forum program and any time someone puts a quote or some other JavaScript parse-able character into it, it breaks my program.
Is there a way either to force JavaScript to recognize it as a string without parsing it as script or, failing that, a function that escapes all scripting within a string that will be dynamic?
I did a search and all I could find were endless webpages on how to escape individual characters with a slash - perhaps my search skills need work.
Are you putting the contents of the signature using a server-side language, dynamically, in a JavaScript string literal? That probably isn't the best way to go; you may want to reconsider the way you are doing it.
For example, a better way to do it could be that you could just have an element on the page for the signature (which doesn't have to be visually distinct) and then get the contents of that for use in the script during JavaScript runtime.
If you still wanted to take the route you are going, you could replace ' with \' (or " with \" if you are using double-quoted strings in your script) and replace \n with \\n, which replaces real newlines with newline escapes.

Categories

Resources