What does f.write << TEMPLATE mean in the below code snippet - ruby-on-rails

File.open("db/quotes/#{id}.json", "w") do |f|
f.write <<TEMPLATE
{
"submitter": "{hash["submitter"]}",
"quote": "{hash["quote"]}",
"attribution": "{hash["attribution"]}"
}
TEMPLATE
end
I understand what this method is doing. I read this code snippet out of a book. It is trying to write to a json to a file with whatever name #{id}.json is. I have never seen it before. Is "<<" an operator? What is "TEMPLATE"? Btw, this it out of the book rebuilding ruby on rails. In the section of rebuilding the Model layer is where i found the code snippet. It could have something to do with the Gem "erubis".

f.write expects a string as an argument and writes that string to the file f.
<<TEMPLATE starts a string that ends at the next occurrence of TEMPLATE. This kind of strings are called heredocs.

It's here-document syntax for string. It's a way to represent a string spanning multiple lines and the indentation will be preserved.
str = <<EOF
this will be the content
of your string
EOF
You can choose whatever word you want where I put EOF.

The other answers point you in the right direction of heredocs.
Technically this is syntax error with the string never terminating.
begin
str = <<EOS
This is my string
EOS
end
Because the EOS at the beginning of the line. The below example works:
begin
str = <<EOS
This is my string
EOS
end
To have correctly indented code you would do the following:
begin
str = <<-EOS
This is my string
EOS
end

Related

Multiple `gsub` in multiple `each` loops getting overriden one by another

Trying to iterate over some phrases, and whenever I find a word, I need to replace it with a link.
phrases = ["hello world", "worldwide"]
words_to_link = ["world", "world"]
I am trying to get:
"hello <a href='world'>world</a><br />worldwide"
My code is:
phrases.each do |ph|
words_to_link.each do |w|
ph.gsub!(w, "<a href='#{w}'>#{w}</a>")
end
end.join("<br />").html_safe
The output of this is:
"hello <a href='<a href='world'>world</a>'><a href='world'>world</a></a><br /><a href='<a href='world'>world</a>'><a href='world'>world</a></a>wide"
On the first run it finds all occurrences of world, but on the second, it goes inside the generated world and gsubs again.
Another problem is the proper regex to only find words by boundaries, I thought it would be /\b(word)\b, but that didn't work.
Any pointers?
I'm a little confused by your question, so may have got the wrong end of the stick here. However, here is an answer by my interpretation:
phrases = ["hello world", "worldwide"]
substitutions = { /\bworld\b/ => "world" }
phrases.each do |ph|
substitutions.each do |pattern, replacement|
ph.gsub!(pattern, "<a href='#{replacement}'>#{replacement}</a>")
end
end
phrases.join("<br />").html_safe
You can use \b in a regex to mark a work boundary, to avoid altering the "worldwide" string. And (I think this is what you wanted?) you can define some mapping between the search/replace terms rather than looping though twice, to avoid the double-replacement.

Groovy- searching and excretion xml code from log file

I have so many texts in log file but sometimes i got responses as a xml code and I have to cut this xml code and move to other files.
For example:
sThread1....dsadasdsadsadasdasdasdas.......dasdasdasdadasdasdasdadadsada
important xml code to cut and move to other file: <response><important> 1 </import...></response>
important xml code to other file: <response><important> 2 </important...></response>
sThread2....dsadasdsadsadasdasdasdas.......dasdasdasdadasdasdasdadadsada
Hindrance: xml code starting from difference numbers of sign (not always start in the same number of sign)
Please help me with finding method how to find xml code in text
Right now i tested substring() method but xml code not always start from this same sign :(
EDIT:
I found what I wanted, function which I searched was indexOf().
I needed a number of letter where String "Response is : " ending: so I used:
int positionOfXmlInLine = lineTxt.indexOf("<response")
And after this I can cut string to the end of the line :
def cuttedText = lineTxt.substring(positionOfXmlInLine);
So I have right now only a XML text/code from log file.
Next is a parsing XML value like BDKosher wrote under it.
Hoply that will help someone You guys
You might be able to leverage XmlSlurper for this, assuming your XML is valid enough. The code below will take each line of the log, wrap it in a root element, and parse it. Once parsed, it extracts and prints out the value of the <important> element's value attribute, but instead you could do whatever you need to do with the data:
def input = '''
sThread1..sdadassda..sdadasdsada....sdadasdas...
important code to cut and move to other file: **<response><important value="1"></important></response>**
important code to other file: ****<response><important value="3"></important></response>****
sThread2..dsadasd.s.da.das.d.as.das.d.as.da.sd.a.
'''
def parser = new XmlSlurper()
input.eachLine { line, lineNo ->
def output = parser.parseText("<wrapper>$line</wrapper>")
if (!output.response.isEmpty()) {
println "Line $lineNo is of importance ${output.response.important.#value.text()}"
}
}
This prints out:
Line 2 is of importance 1
Line 3 is of importance 3

ruby regex with quotes

I'm trying to pass more than one regex parameter for parts of a string that needs to be replaced. Here's the string:
str = "stands in hall "Let's go get to first period everyone" Students continue moving to seats."
Here is the expected string:
str = "stands in hall "Let's go get to first period everyone" Students continue moving to seats."
This is what I tried:
str.gsub(/'|"/, "'" => "\'", """ => "\"")
This is what I got:
"stands in hall \"Let's go get to first period everyone\" Students continue moving to seats."
How do I get the quotes in while sending in two regex parameters using gsub?
This is an HTML unescaping problem.
require 'cgi'
CGI.unescape_html(str)
This gives you the correct answer.
From my comments on this question:
Your updated version is correct. The only reason the slashes are in your final line of code is that it's an escape sequence so that you don't mistakenly think the first slash is used to terminate the string. Try assigning your output and printing it:
str1 = str.gsub(/'|"/, "'" => "\'", """ => "\"")
puts str1
and you'll see that the slashes are gone when str1 is printed using puts.
The difference is that autoevaluating variables within irb (which is what I assume you're doing to execute this sample code) automatically calls the inspect method, which for string variables shows the string in its entirety.
Because I did not understand unescaping characters I found an alternative solution that might be the "rails-way"
Can you use <%= raw 'some_html' %>
My final solution ended up being this instead of messy regex and requiring CGI
<%= raw evidence_score.description %>
Unescaping HTML string in Rails

changing a variable using gets.chomp()

im trying to write to a file using this code:
puts "-------------------- TEXT-EDITOR --------------------"
def tor(old_text)
old_text = gets.chomp #
end
$epic=""
def torr(input)
tore= $epic += input + ", "
File.open("tor.txt", "w") do |write|
write.puts tore
end
end
loop do
output = tor(output)
torr(output)
end
i have read the ultimate guide to ruby programming
and it says if i want to make a new line using in the file im writing to using File.open
i must use "line one", "line two
how can i make this happend using gets.chomp()? try my code and you will see what i mean
thank you.
The gets method will bring in any amount of text but it will terminate when you hit 'Enter' (or once the STDIN receives \n). This input record separator is stored in the global variable $/. If you change the input separator in your script, the gets method will actually trade the 'Enter' key for whatever you changed the global variable to.
$/ = 'EOF' # Or any other string
lines = gets.chomp
> This is
> multilined
> textEOF
lines #=> 'This is\nmultilined\ntext'
Enter whatever you want and then type 'EOF' at the end. Once it 'sees' EOF, it'll terminate the gets method. The chomp method will actually strip off the string 'EOF' from the end.
Then write this to your text file and the \n will translate into new lines.
File.open('newlines.txt', 'w') {|f| f.puts lines}
newlines.txt:
This is
multilined
text
If you dont use .chomp() the \n character will be added whenever you write a new line, if you save this to the file it also will have a new line. .chomp() removes those escape characters from the end of the input.
If this doesnt answer your question, i am sorry i dont understand it.

Truncate Markdown?

I have a Rails site, where the content is written in markdown. I wish to display a snippet of each, with a "Read more.." link.
How do I go about this? Simple truncating the raw text will not work, for example..
>> "This is an [example](http://example.com)"[0..25]
=> "This is an [example](http:"
Ideally I want to allow the author to (optionally) insert a marker to specify what to use as the "snippet", if not it would take 250 words, and append "..." - for example..
This article is an example of something or other.
This segment will be used as the snippet on the index page.
^^^^^^^^^^^^^^^
This text will be visible once clicking the "Read more.." link
The marker could be thought of like an EOF marker (which can be ignored when displaying the full document)
I am using maruku for the Markdown processing (RedCloth is very biased towards Textile, BlueCloth is extremely buggy, and I wanted a native-Ruby parser which ruled out peg-markdown and RDiscount)
Alternatively (since the Markdown is translated to HTML anyway) truncating the HTML correctly would be an option - although it would be preferable to not markdown() the entire document, just to get the first few lines.
So, the options I can think of are (in order of preference)..
Add a "truncate" option to the maruku parser, which will only parse the first x words, or till the "excerpt" marker.
Write/find a parser-agnostic Markdown truncate'r
Write/find an intelligent HTML truncating function
Write/find an intelligent HTML truncating function
The following from http://mikeburnscoder.wordpress.com/2006/11/11/truncating-html-in-ruby/, with some modifications will correctly truncate HTML, and easily allow appending a string before the closing tags.
>> puts "<p><b>Something</p>".truncate_html(5, at_end = "...")
=> <p><b>Someth...</b></p>
The modified code:
require 'rexml/parsers/pullparser'
class String
def truncate_html(len = 30, at_end = nil)
p = REXML::Parsers::PullParser.new(self)
tags = []
new_len = len
results = ''
while p.has_next? && new_len > 0
p_e = p.pull
case p_e.event_type
when :start_element
tags.push p_e[0]
results << "<#{tags.last}#{attrs_to_s(p_e[1])}>"
when :end_element
results << "</#{tags.pop}>"
when :text
results << p_e[0][0..new_len]
new_len -= p_e[0].length
else
results << "<!-- #{p_e.inspect} -->"
end
end
if at_end
results << "..."
end
tags.reverse.each do |tag|
results << "</#{tag}>"
end
results
end
private
def attrs_to_s(attrs)
if attrs.empty?
''
else
' ' + attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ')
end
end
end
Here's a solution that works for me with Textile.
Convert it to HTML
Truncate it.
Remove any HTML tags that got cut in half with
html_string.gsub(/<[^>]*$/, "")
Then, uses Hpricot to clean it up and close unclosed tags
html_string = Hpricot( html_string ).to_s
I do this in a helper, and with caching there's no performance issue.
You could use a regular expression to find a line consisting of nothing but "^" characters:
markdown_string = <<-eos
This article is an example of something or other.
This segment will be used as the snippet on the index page.
^^^^^^^^^^^^^^^
This text will be visible once clicking the "Read more.." link
eos
preview = markdown_string[0...(markdown_string =~ /^\^+$/)]
puts preview
Rather than trying to truncate the text, why not have 2 input boxes, one for the "opening blurb" and one for the main "guts". That way your authors will know exactly what is being show when without having to rely on some sort of funkly EOF marker.
I will have to agree with the "two inputs" approach, and the content writer would need not to worry, since you can modify the background logic to mix the two inputs in one when showing the full content.
full_content = input1 + input2 // perhaps with some complementary html, for a better formatting
Not sure if it applies to this case, but adding the solution below for the sake of completeness. You can use strip_tags method if you are truncating Markdown-rendered contents:
truncate(strip_tags(markdown(article.contents)), length: 50)
Sourced from:
http://devblog.boonecommunitynetwork.com/rails-and-markdown/
A simpler option that just works:
truncate(markdown(item.description), length: 100, escape: false)

Resources