Ruby/Development/Embedded Ruby

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Embedded in the string are a pair of template tags, <%= and %>.

#!/usr/bin/env ruby
require "erb"
person = "myValue!"
temp = ERB.new( "Hello, <%= person %>" )
puts temp.result( binding ) # => Hello, myValue!



Embedded Ruby

# Embedded Ruby (ERB or eRuby) embeds arbitrary Ruby code in text files. 
# The code is executed when the file is processed. 
# ERB comes with the Ruby distribution. 
# It"s very common to embed code in HTML or XHTML.
#!/usr/bin/env ruby
require "erb"
person = "myValue!"
temp = ERB.new( "Hello, <%= person %>" )
puts temp.result( binding ) # => Hello, myValue!



ERB tags in a string

#!/usr/bin/env ruby
require "erb"
document = %[
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title><%= @name %></title>
</head>
<body>
<h1><%= @name %></h1>
<p><b>Breed:</b> <%= @breed %></p>
<p><b>Sex:</b> <%= @sex %></p>
<h2>Foals</h2>
<ul><% @foals.each do |foals| %>
 <li><%= foals %></li> <% end %>
</ul>
</body>
</html>
]
class Horse
  def initialize( name, breed, sex )
   @name = name
   @breed = breed
   @sex = sex
   @foals = []
  end
  def foal( name )
    @foals << name
  end
  def context
    binding
  end
end
output = ERB.new( document )
horse = Horse.new( "A", "Q", "M" )
horse.foal( "D" )
horse.foal( "P" )
output.run( horse.context )



ERB template tags

Tag                Description
<% ... %>          Ruby code; inline with output.
<%= ... %>         Ruby expression; replace with result.
<%# ... %>         Comment; ignored; useful in testing.
%                  A line of Ruby code; treated as <% .. %>; set with trim_mode argument in ERB.new.
%%                 Replace with % if it is the first thing on a line and % processing is used.
<%% ... %%>        Replace with <% or %> , respectively.



Nested ERB block

require "erb"
template = %q{
<% if problems.empty? %>
  it is true
<% else %>
  Here is else
  <% problems.each do |problem, line| %>
    * <%= problem %> on line <%= line %>
  <% end %>
<% end %>}.gsub(/^\s+/, "")
template = ERB.new(template, nil, "<>")
problems = [["Use of is_a? ", 23],
            ["eval() is dangerous", 44]]
template.run(binding)