How to show variables from Ruby in HTML - ruby-on-rails

I have many variables like:
#a = '<b>bla bla</b>'
They appear in the browser in the same way. I need code that can translate them into HTML so that they will appear as:
bla bla

Use this to print it as HTML
#a = '<b>bla bla</b>'.html_safe
html_safe() will not escape any characters.

Maybe you need to use html helpers?
http://sraji.wordpress.com/2011/05/26/how-to-display-html-tags-in-rails-helper-methods/
http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/

Related

Passing raw HTML to haml file

Is it possible to pass pre formatted HTML to the haml file. For example I pass a variable such as:
my_text = "<b>this is bold</b>"
Then in my haml file:
%p
=#my_text
I was hoping it would display This is bold
But it just returns the original string and ignores the tags surrounding "this is bold"
The goal is to highlight certain key words("one" and "two" in this example), here's a better example:
#my_text = "This <b>one</b> plus <b>one</b> is a total of <b>two</b>"
Not sure what you want to achieve, but i'd recommend that you keep your markup in the haml and plug in your copy in the instance variable like this.
MyTextController.rb
#my_text = this is bold
my_text.html.haml
%b
= #my_text
Edit after further clarification.
You can use sanitize helper for this.
my_text.html.haml
%p
= sanitize(#my_text, tags: %w(b))
Ahh I figured it out, looks like you can do:
%p
= raw #my_text

Using regex to get title

I'm not sure how I'd select an title with regex. I've tried
match(/<title>(.*) .*<\/title>/)[1]
but that doesn't match anything.
This is the response body I'm trying to select from.
Trying to select "title I need to select."
The reason it doesn't work is because of the itemprop=\"name\" property. To fix this, you can match it as well:
# copy-paste from the page you provided
html = '<!doctype html>\n<html lang=\"en\" itemscope itemtype=\"https://schema.org/WebPage\">\n<head>\n<meta charset=\"utf-8\"><meta name=\"referrer\" content=\"always\" />\n<title itemprop=\"name\">title I need to select.</title>\n<meta itemprop=\"description\" name=\"description\" content=\\'
html.match(/<title.*?>(.*)<\/title>/)[1] # => "title I need to select."
.*? basically means "match as many characters are needed, but not more"
However, as other have pointed out, regexes are not ideal for html parsing. Instead, you could use a popular ruby gem for that purpose - Nokogiri:
require 'nokogiri'
page = Nokogiri.parse(html)
page.css('title').text # => "title I need to select."
Note that it can handle even malformed html like is the case here.
If you're looking for a much more robust XML/HTML parser, try using Nokogiri which supports XPath.
This post explains why
Use xPath or Regex?
require "nokogiri"
string = "<title itemprop=\"name\">title I need to select.</title>"
html_doc = Nokogiri::HTML(string)
html_doc.xpath("//title").first.text
Here's the regexp that will give you what you want:
<title.*>(.*)<\/title>
As was mentioned, there are better ways to parse HTML. You might want to check out something like Nokogiri.
When I have to get elements from XML I like to convert it to a hash
from_xml(xml, disallowed_types = nil) public
Returns a Hash containing a collection of pairs when the key is the
node name and the value is its content
# http://apidock.com/rails/Hash/from_xml/class
now you can do something like
hash = Hash.from_xml('XML')
hash.title # my favorite book
One solution would be to use the following pattern:
<title.*?>(.*?)<\/title>
https://regex101.com/r/piwm5H/1
Use a HTML/XML parser when dealing with XML or HTML data, except for extremely simple cases. HTML and XML are too complicated for normal regular expressions.
Using Nokogiri I'd do:
require 'nokogiri'
some_html = '
<html>
<head>
<title>the title</title>
</head>
</html>
'
doc = Nokogiri::HTML(some_html)
doc.title # => "the title"
Nokogiri already has a method to return the title so you can take advantage of that. Or, you can do it the normal way:
doc.at('title').text # => "the title"
The problem with a regular expression is that HTML could be written in many ways:
<title>foo</title>
or:
<title>
foo
</title>
or even:
<title>foo
</head>
which, while not correct, will be accepted by browsers and fixed up by Nokogiri which will then still work. Writing a pattern to handle those variants is a pain and error-prone. It only gets worse as the HTML gets more complex, especially when you don't control the generation of the content.

Ruby - html tags are not converted to formatting tags

I have a simple form, where a user can write some text and this text will be send to his email. This process works fine, but I have a problem with the text, that user wrote - in the email is displayed following:
["sadgsdah\r\nsdh\r\ndsf\r\nh\r\nfdhdfhdfh\r\n\r\n\r\n\r\nfdh\r\ndf\r\njh"]
why there are the brackets and the \n and \r chars?
Before than I give the variable with the content into the email template, I tried to do following:
mess_body = params[:contact][:message].to_s.html_safe
But unfortunately this didn't help me... what I am doing wrong?
To convert newlines to look right in html, use simple_format to convert the text.
First of all
mess_body = params[:contact][:message]
returns a array, not a single thing. That is why you get the [" and "] around the output.
you could get the first element like this:
mess_body = params[:contact][:message][0]
Furthermore \n\r are line endings of a text box. Assuming that the e-mail you're sending is HTML the \n\r should be replaced by <br> in the String

Rails 3.1 HAML escaping too much on a an `:escaped` chunk, how to control it so that it only escapes ampersands?

I have a chunk of code provided by Wistia to embed videos into a page. This source is embedable raw html and they include some ampersands in it directly. Of course my w3c validator yells at me all day long and with these in it I'm getting hundreds of errors like:
& did not start a character reference. (& probably should have been escaped as &.)
My view is in HAML so I'm assuming that I needed to escape the sequence, which I happily did with:
:escape
<object width="...
Upon doing this the video no longer loads as it has escaped the entire string with <object width=" ... etc.
How would one properly escape such sequences programmatically vs manually altering the inserted string each time a new update is made in Rails 3.1 with HAML?
You'll probably want to put your HTML into its own partial, then render it into a string and do a String#gsub on it.
Put your Wistia HTML into a partial called something like app/views/shared/_wistia.html
Then create a helper that looks like:
def embed_video(partial)
html = render_to_string(:partial => "shared/#{partial}")
html.gsub '&', '&'
end
And in your HAML, just put = embed_video 'wistia' wherever you want the video to be inserted.

Rails only escape certain sections of content

I'm looking to turn all words preceeded by a # (ie #stackoverflow) into a link that when clicked through will link to the search page with the word as a query.
I tried this recently and got the right HTML being returned, but because content is automatically escaped it showed as:
This is some content something
My question is: Is there any way to only apply html_safe to every part of the content except for these links?
If your tags are simple alphanumeric strings (i.e. nothing that needs to be HTML or URL encoded), then you could do something like this:
s = ERB::Util.html_escape(text_to_be_linkified).gsub(/#(\w+)/, '\1').html_safe
Then s.html_safe? will be true and <%= ... %> will pass the result through as-is. If you put this in a view helper, then you shouldn't need the ERB::Util. prefix on html_escape. If you do need to worry about URL or HTML encoding then you could modify the gsub replacement string appropriately.
For example:
> s = ERB::Util.html_escape('<pancakes & #things').gsub(/#(\w+)/, '\1').html_safe
> puts s.html_safe?
true
> puts s
<pancakes & things

Resources