This question already has an answer here:
String interpolation in Ruby doesn't work?
(1 answer)
Closed 5 years ago.
I've been trying to show random images everytime a user post something.
I have images name "kejang (#).png" # ranging from 1 to 21.
So I have done this.
<div class = 'article_header'>
<div class = 'article_img'>
<% kj_num = rand(20) + 1 %>
<%= kj_num %>
<%= image_tag 'kejang (#{kj_num}).PNG' %>
</div>
It does run on the server but returns no image, only 'x' marked crashed images.
I wondered where it went wrong and altered #{kj_num} with regular number and it worked. (i.e, I put 2 or 3 instead of #{kj_num} and it worked.)
Why is #{kj_num} not working ??
Rails interpretting #{variable} as a simple text. How should I change my code?
#{} vs. single vs. double quotes
Here you need to use double quotes (") rather than single quotes (')
<div class = 'article_header'>
<div class = 'article_img'>
<% kj_num = rand(20) + 1 %>
<%= kj_num %>
<%= image_tag "kejang (#{kj_num}).PNG" %>
</div>
</div>
String interpolation is the process of converting placeholders inside a string to the values they represent, in order to produce a dynamic string. You probably use it all the time without realizing just how cool it works under the hood, and how you can leverage this power in your own classes.
person = 'World'
puts "Hello, #{person}!"
https://kconrails.com/2010/12/08/ruby-string-interpolation/
You are trying to use string interpolation inside single quotes which will not work. You have to use double quotes instead
Here is an example to understand it,
jruby-1.7.13 :001 > name = 'ajinkya'
=> "ajinkya"
jruby-1.7.13 :002 > 'hello, #{name}'
=> "hello, \#{name}"
jruby-1.7.13 :003 > "hello, #{name}"
=> "hello, ajinkya"
More detailed explanation about Double vs single quotes
Related
I am trying to have the time output in a nice way.
Here is my code in new
<%= form_for #reservation do |f| %>
<span><label>Pick up time</label></span>
<%= f.time_select :time,ampm: true, class: "textbox"%></span>
<% end %>
And here is in the output file
<strong>Pick up Time:</strong> <%= #reservation.time.strftime("%H:%M") %>
I got this error
undefined method `strftime' for "{1=>2019, 2=>7, 3=>7, 4=>16, 5=>0}":String
Did you mean? strip
Please some one help me to fix this
As Sebastian mentions in a comment; it looks as though your time object is a Hash. To call strftime your object needs to be a :datetime.
To fix this you should change the column type in your database to be that of datetime (As well as changing your forms to save a datetime value).
An alternative would be to build the string you want to display manually using what is in time (not using strftime).
If you want to use only this hash then you need to parse it to date time like below
a = {1=>2019, 2=>7, 3=>7, 4=>16, 5=>0}
time = (a.values.first(3).join("/") + " "+ a.values.last(2).join(":")).to_datetime.strftime("%I:%M %p")
After parsing to date and time you can perform any method of date time.
(#reservation.to_date).strftime("%H:%M")
It seems to be an order of operations - first change string to date then transform. Something similar worked for me in Workato just now.
I need to print stored html symbols in an email. Why isn't this working? It prints the symbol string instead of the symbol. ex: ↺ instead of ↺
here is a example of my code:
<% event_symbol = "↺"%>
<%="#{event_symbol}"%>
Add raw:
<% event_symbol = "↺"%>
<%=raw event_symbol%>
I have retrieve this key/value from a hash using the facebook api
"message":"Next Practice:\n\nDate: 04.05.2014\nTime: 10:00-12:00\nVenue: Llandaff Fields\n\nAll welcome
but when i save it to my model i seem to lose all the special characters, i.e \n. Is there a way to save the value as it is returned so that i can use the \n when outputting to my view using .html_safe
This is how i am retrieving the data
def get_feed
fb_access_token = access_token
uri = URI(URI.escape "https://graph.facebook.com/#{VANDALS_ID}/posts/?#{fb_access_token}")
response = HTTParty.get(uri)
results = JSON.parse(response.body)
formatted_data(results)
end
anything i need to be doing to keep that string with \n left in it
Thanks
When I run the following code:
raw_json = '{"message":"Next Practice:\n\nDate: 04.05.2014\nTime: 10:00-12:00\nVenue: Llandaff Fields\n\nAll welcome"}'
parsed_json = JSON.parse(raw_json)
puts parsed_json['message']
# => Next Practice:
# => Date: 04.05.2014
# => Time: 10:00-12:00
# => Venue: Llandaff Fields
# => All welcome
So the \n is kept (it is parsed, and shown as real new-line). I also don't believe that saving this to your model erased the new lines.
Where I think your real problem lies is that in HTML new lines (\n) are not rendered as new lines at all, but as spaces. To render them as new lines, you need to replace them with breaks (<br>).
So you can try using the following on your ERB:
<div class=message><%= feed.message.gsub("\n", "<br>").html_safe %></div>
Your new-lines will now be rendered on the page.
I'm working with Ruby on Rails, Is there a way to strip html from a string using sanitize or equal method and keep only text inside value attribute on input tag?
If we want to use this in model
ActionView::Base.full_sanitizer.sanitize(html_string)
which is the code in "strip_tags" method
There's a strip_tags method in ActionView::Helpers::SanitizeHelper:
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_tags
Edit: for getting the text inside the value attribute, you could use something like Nokogiri with an Xpath expression to get that out of the string.
Yes, call this: sanitize(html_string, tags:[])
ActionView::Base.full_sanitizer.sanitize(html_string)
White list of tags and attributes can be specified as bellow
ActionView::Base.full_sanitizer.sanitize(html_string, :tags => %w(img br p), :attributes => %w(src style))
Above statement allows tags img, br and p and attributes src and style.
I've used the Loofah library, as it is suitable for both HTML and XML (both documents and string fragments). It is the engine behind the html sanitizer gem. I'm simply pasting the code example to show how simple it is to use.
Loofah Gem
unsafe_html = "ohai! <div>div is safe</div> <script>but script is not</script>"
doc = Loofah.fragment(unsafe_html).scrub!(:strip)
doc.to_s # => "ohai! <div>div is safe</div> "
doc.text # => "ohai! div is safe "
How about this?
white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
WHITELIST = ['p','b','h1','h2','h3','h4','h5','h6','li','ul','ol','small','i','u']
[Your, Models, Here].each do |klass|
klass.all.each do |ob|
klass.attribute_names.each do |attrs|
if ob.send(attrs).is_a? String
ob.send("#{attrs}=", white_list_sanitizer.sanitize(ob.send(attrs), tags: WHITELIST, attributes: %w(id style)).gsub(/<p>\s*<\/p>\r\n/im, ''))
ob.save
end
end
end
end
If you want to remove all html tags you can use
htm.gsub(/<[^>]*>/,'')
This is working for me in rails 6.1.3:
.errors-description
= sanitize(message, tags: %w[div span strong], attributes: %w[class])
You can do .to_plain_text:
#my_string = <p>My HTML String</p>
#my_string.to_plain_text
=> My HTML String
I have an untrusted string that I want to show as text in an HTML page. I need to escape the chars '<' and '&' as HTML entities. The less fuss the better.
I'm using UTF8 and don't need other entities for accented letters.
Is there a built-in function in Ruby or Rails, or should I roll my own?
Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.
CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo "bar" <baz>"
The h helper method:
<%=h "<p> will be preserved" %>
In Ruby on Rails 3 HTML will be escaped by default.
For non-escaped strings use:
<%= raw "<p>hello world!</p>" %>
ERB::Util.html_escape can be used anywhere. It is available without using require in Rails.
An addition to Christopher Bradford's answer to use the HTML escaping anywhere,
since most people don't use CGI nowadays, you can also use Rack:
require 'rack/utils'
Rack::Utils.escape_html('Usage: foo "bar" <baz>')
You can use either h() or html_escape(), but most people use h() by convention. h() is short for html_escape() in rails.
In your controller:
#stuff = "<b>Hello World!</b>"
In your view:
<%=h #stuff %>
If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as <b>Hello World!</b>.
It will appear an be displayed as <b>Hello World!</b>
Comparaison of the different methods:
> CGI::escapeHTML("quote ' double quotes \"")
=> "quote ' double quotes ""
> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote ' double quotes ""
> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote ' double quotes ""
I wrote my own to be compatible with Rails ActiveMailer escaping:
def escape_html(str)
CGI.escapeHTML(str).gsub("'", "'")
end
h() is also useful for escaping quotes.
For example, I have a view that generates a link using a text field result[r].thtitle. The text could include single quotes. If I didn't escape result[r].thtitle in the confirm method, the Javascript would break:
<%= link_to_remote "#{result[r].thtitle}", :url=>{ :controller=>:resource,
:action =>:delete_resourced,
:id => result[r].id,
:th => thread,
:html =>{:title=> "<= Remove"},
:confirm => h("#{result[r].thtitle} will be removed"),
:method => :delete %>
<a href="#" onclick="if (confirm('docs: add column 'dummy' will be removed')) { new Ajax.Request('/resource/delete_resourced/837?owner=386&th=511', {asynchronous:true, evalScripts:true, method:'delete', parameters:'authenticity_token=' + encodeURIComponent('ou812')}); }; return false;" title="<= Remove">docs: add column 'dummy'</a>
Note: the :html title declaration is magically escaped by Rails.