Skip to content

Instantly share code, notes, and snippets.

@RichMorin
Created January 2, 2017 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichMorin/055bb69484207885ab51e7cdd6ac44dd to your computer and use it in GitHub Desktop.
Save RichMorin/055bb69484207885ab51e7cdd6ac44dd to your computer and use it in GitHub Desktop.
demonstrate newline-handling nit
#!/usr/bin/env ruby
#
# erb_nl_nit - minimal example of Embedded Ruby newline nit
#
# The Embedded Ruby implementation for Sinatra removes (some) newlines.
# Basically, if an interpolated string is on a line by itself (no text
# either before or after), the newline goes away. The Ruby ERB library
# does not exhibit this problem.
#
# The input and results are displayed on STDOUT and the output web page.
# (Do a "View Source" to see the latter.)
require 'erb'
require 'sinatra'
get '/' do
tests = [
"<%= 'T1' %>\n...\n", # Sinatra discards newline.
"<%= 'T2 ' %>\n...\n", # Sinatra discards newline.
"x <%= 'T3' %>\n...\n", # Sinatra retains newline.
"<%= 'T4' %> \n...\n", # Sinatra retains newline.
]
puts "\nSinatra erb results:"
results_1 = tests.map do |input|
result = erb(input)
puts " #{ input.inspect } => #{ result.inspect }"
result
end
puts "\nRuby ERB results:"
results_2 = tests.map do |input|
result = ERB.new(input).result(binding)
puts " #{ input.inspect } => #{ result.inspect }"
result
end
puts
html = <<EOT
<pre>
Sinatra erb results:
#{ results_1.join("\n") }
Ruby ERB results:
#{ results_2.join("\n") }
</pre>
EOT
end
sample_output = <<EOT
$ erb_nl_nit
== Sinatra (v1.4.7) has taken the stage on 4567 for development
with backup from Thin
Thin web server (v1.7.0 codename Dunder Mifflin)
Maximum connections set to 1024
Listening on localhost:4567, CTRL+C to stop
Sinatra erb results:
"<%= 'T1' %>\n...\n" => "T1...\n"
"<%= 'T2 ' %>\n...\n" => "T2 ...\n"
"x <%= 'T3' %>\n...\n" => "x T3\n...\n"
"<%= 'T4' %> \n...\n" => "T4 \n...\n"
Ruby ERB results:
"<%= 'T1' %>\n...\n" => "T1\n...\n"
"<%= 'T2 ' %>\n...\n" => "T2 \n...\n"
"x <%= 'T3' %>\n...\n" => "x T3\n...\n"
"<%= 'T4' %> \n...\n" => "T4 \n...\n"
::1 - - [01/Jan/2017:18:02:54 -0800] "GET / HTTP/1.1" 200 126 0.0141
EOT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment