How to write correctly <%= t('.title_#{Time.now.wday}') %>? - ruby-on-rails

Usually to add a word (for my multilanguage website) I use this system: <%= t('.title') %>
Now in config/locales/en.yml, I added something like this:
en:
home:
title: Title
title_0: Finally Sunday! Watch this title
title_1: Hey! It's monday! This is the Title
And I want to use Time.now.wday and to create something like <%= t('.title_#{Time.now.wday}') %>
But it doesn't work. How to write it correctly?

That's because you need double quotes for string interpolation in Ruby. Just replace
<%= t('.title_#{Time.now.wday}') %>
for
<%= t(".title_#{Time.now.wday}") %>
although it maybe should be
<%= t("home.title_#{Time.now.wday}") %>
because title, title_0 and title_1 are nested under home

Interpolation does not work with single quotes
That means that:
puts "Works in double quoted strings: #{1 + 2}."
puts 'Not not work in single quoted strings: #{1 + 2}.'
will print out:
"Works in double quoted strings: 3."
"Does not work in single quoted strings: #{1 + 2}."
source: http://ruby-for-beginners.rubymonstas.org/bonus/string_interpolation.html

Related

Rails dealing with single and double quotes

I have a problem in dealing with single quoted characters in en.yml, in my erb file I have a line of code,
<input type="text" class="something" id="myUsername" placeholder='<%= I18n.t("entries.email") %>' value="<%= user.email%>">, and corresponding yml is,
entries:
email: "Entrer le nom d'utilisateur"
The problem here is that the string after apostrophe (d') gets truncated, I could resolve it by using double quoted string for placeholder, that way it worked, but is that a good solution, can someone suggest me a better way to deal with this.
Note: Tried escaping single quote but didn't work for some reason.
Write it using text_field_tag helper :
<%=
text_field_tag "user[email]", user.email, id: "myUsername",
placeholder: I18n.t("entries.email"), class: "something"
%>
It is easy to use.

How to render array of lines to <textarea>?

I'm on Ruby 2.0 and Rails 4, and trying to render an array of lines to f.text_area form helper using:
<%= f.text_area :sources_text, value: ['1', '2'].join('\n') %>
I expect to get:
1
2
as the <textarea> value but I get:
1\n2
What I'm doing wrong?
In the helper the value is being rendered as a string.
So to have
1
2
you have to have the value be "1\n2"
so if you have an array t then:
<%t=['1','2']%>
<%= f.text_area :sources_text, value: t.join("\n") %>
and you will have in the text area
1
2
Use: "\n". The '\n' version used single quotes '', which escape almost nothing.
Dev tip: Always prefer '' unless you actually need ""'s special powers (which you do need, here).

image_tag syntax with or without "" - with method - ruby

To "" or not to "" - that is the question.
<%= image_tag(#profile.image, :size => "80x80", :alt => "Picture") %>
or
<%= image_tag("#profile.image", :size => "80x80", :alt => "Picture") %>
Ask yourself this questions: Do you ever quote variable's in any programming language? Probably not. Some languages handle variables inside of double quotes so that you can write a string like this: "My name is <variable>". The other way to do it is "My name is "+<variable>
So basically no you do not want to quote "#profile.image".
Using "#profile.image" will put the src attribute equal to #profile.image, NOT the value of #profile.image.
Don't use the quotes, unless your image is called "#profile.image".
If the image's filename is #profile.image, then use quotes. If #profile.image contains the name of the image file, don't.

Add a link to a label/hint in formtastic with haml

I'm trying to add a link to a checkbox in formtastic, using haml. It looks like formtastic removes all ruby/haml/html syntax from the text for the label or hint when it parses it.
That is, this doesn't work:
= f.input :terms, label: '=link_to \'Here\', path_to_link', hint: '=link_to \'Other Place\', path_to_other_link', as: :boolean
Is there anything that will other than writing another div outside of this input? Or am I going about this all wrong? I'm a rails/haml/formtastic noob.
if you use ' for string quotation, you're basically telling ruby not to parse that content.
try something like this instead:
= f.input :terms, label: link_to('Here', path_to_link), hint: link_to('Other place', path_to_other_link), as: :boolean
Formtastic::FormBuilder.escape_html_entities_in_hints_and_labels = false
In your formtastic initializer
If you mark the string passed to label: or hint: as HTML safe then Haml doesn't escape it.
= f.input :terms,
label: "Please accept our ".html_safe + link_to('Terms and Conditions', path_to_link)
19 ways tried, with either the hyperlink being encoded or html_safe replacing hyphens in the url ???
This is what worked for me
<%= f.label :cookies do
"Do you agree to our #{link_to('Cookies Policy', 'http://www.your-­url.co.uk/privacypolicy')}".html_safe
end %>
The specific use of " and ' appears significant.

Rails escape_javascript creates invalid JSON by escaping single quotes

The escape_javascript method in ActionView escapes the apostrophe ' as backslash apostrophe \', which gives errors when parsing as JSON.
For example, the message "I'm here" is valid JSON when printed as:
{"message": "I'm here"}
But, <%= escape_javascript("I'm here") %> outputs "I\'m here", resulting in invalid JSON:
{"message": "I\'m here"}
Is there a patch to fix this, or an alternate way to escape strings when printing to JSON?
Just call .to_json on a string and it will be escaped properly e.g.
"foo'bar".to_json
I ended up adding a new escape_json method to my application_helper.rb, based on the escape_javascript method found in ActionView::Helpers::JavaScriptHelper:
JSON_ESCAPE_MAP = {
'\\' => '\\\\',
'</' => '<\/',
"\r\n" => '\n',
"\n" => '\n',
"\r" => '\n',
'"' => '\\"' }
def escape_json(json)
json.gsub(/(\\|<\/|\r\n|[\n\r"])/) { JSON_ESCAPE_MAP[$1] }
end
Anyone know of a better workaround than this?
May need more details here, but JSON strings must use double quotes. Single quotes are okay in JavaScript strings, but not in JSON.
I had some issues similar to this, where I needed to put Javascript commands at the bottom of a Rails template, which put strings into jQuery.data for later retrieval and use.
Whenever I had a single-quote in the string I'd get a JavaScript error on loading the page.
Here is what I did:
-content_for :extra_javascript do
:javascript
$('#parent_#{parent.id}').data("jsonized_children", "#{escape_javascript(parent.jsonized_children)}");
Already there is an issue in github/rails
https://github.com/rails/rails/issues/8844
Fix to mark the string as html_safe
<%= escape_javascript("I'm here".html_safe) %>
or even better you can sanitize the string
<%= sanitize(escape_javascript("I'm here")) %>
<%= escape_javascript(sanitize("I'm here")) %>

Resources