HOME

TheInfoList



OR:

Embedded Ruby (also shortened as ERB) is a templating system that embeds
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sap ...
into a text document. It is often used to embed Ruby code in an
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript ...
document, similar to ASP and JSP, and
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
and other server-side scripting languages. The templating system of eRuby combines Ruby code and plain text to provide flow control and variable substitution, thus making the combined code easier to maintain. The View module of
Ruby on Rails Ruby on Rails (simplified as Rails) is a server-side web application framework written in Ruby under the MIT License. Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web p ...
is responsible for displaying the response or output on a browser. In its simplest form, a view can be a piece of
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript ...
code which has some static content. For most applications, just having static content may not be enough. Many Ruby on Rails applications will require dynamic content created by the controller (action method) to be displayed in their view. This is made possible by using Embedded Ruby to generate templates which can contain dynamic content. Embedded Ruby allows ruby code to be embedded in a view document. This code gets replaced with proper value resulted from the execution of the code at run time. But, by having the ability to embed code in a view document, we risk bridging the clear separation present in the MVC frame. It is thus the responsibility of the developer to make sure that there is a clear separation of responsibility among the model, view and controller modules of his/her application.


Usage

eRuby allows Ruby code to be embedded within a pair of <% and %>
delimiter A delimiter is a sequence of one or more characters for specifying the boundary between separate, independent regions in plain text, mathematical expressions or other data streams. An example of a delimiter is the comma character, which acts ...
s. These embedded code blocks are then evaluated in-place (they are replaced by the result of their evaluation). Apart from creating web pages, eRuby can also be used to create XML Documents,
RSS RSS ( RDF Site Summary or Really Simple Syndication) is a web feed that allows users and applications to access updates to websites in a standardized, computer-readable format. Subscribing to RSS feeds can allow a user to keep track of many d ...
feeds and other forms of structured text files. eRuby dynamically generates static files based on templates. These functionalities of eRuby can be found in the ERB Library. Different types of tag markers used in ERB templates are: # Expression tags # Execution tags # Comment tags


Expression tags

<%= %> : This indicates that the tag encloses an expression. Such a tag starts with an opening tag delimiter followed by an equal to symbol and ends with an end tag
delimiter A delimiter is a sequence of one or more characters for specifying the boundary between separate, independent regions in plain text, mathematical expressions or other data streams. An example of a delimiter is the comma character, which acts ...
. During the rendering of the
template Template may refer to: Tools * Die (manufacturing), used to cut or shape material * Mold, in a molding process * Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs Co ...
, this piece of code gets substituted with the result of the code. If the evaluated result is not a string, it gets converted to a string before it is rendered. For example: require 'erb' x = 500 template = ERB.new("The value of x is: <%= x %>") puts template.result(binding) The resulting text looks like this: The value of x is: 500


Execution tags

<% %> : Code enclosed in such tags is called as a
scriptlet In JavaServer Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in the HTML-like JSP code. The scriptlet is everything inside the tags. Between these the user can add any valid Scriptlet i.e. any valid Java Code. In AppleScr ...
. The code in such a tag gets executed and its result gets replaced in place of the scriptlet. Such tags must have a matching <% end %> tag to denote the end of a functional block. For example:
    <% 4.times do %>
  • list item
  • <% end %>
In the above example, the text list item gets printed four times. The
scriptlet In JavaServer Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in the HTML-like JSP code. The scriptlet is everything inside the tags. Between these the user can add any valid Scriptlet i.e. any valid Java Code. In AppleScr ...
produces no text on its own, it only makes the enclosed statement to run multiple times. The output of above code:
* list item * list item * list item * list item


Comments tags

<%# %> : Contents of comment tags don't get rendered in the output. Such tags start with an open tag delimiter followed by a hash symbol and end with an end tag delimiter. Example of a comment tag is shown below: <%# ruby code %> This is the same as a comment in Ruby. All Ruby code after the # is ignored and generates nothing.


Other tags

Other things common in eRuby are simply common in Ruby, such as string substitution with #, which is similar in languages such as
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
or
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
. Newlines in eRuby can be suppressed by adding a hyphen at the beginning of the end tag delimiter. For example: <%2.times do -%> <%= @name %> <% end -%> In the output of the above code, the value of name gets printed twice in the same line.


Implementations

There are several implementations of eRuby, namely: # ERB # erubis # ember


erb

'
erb
'' is an implementation of eRuby written purely in the Ruby programming language and included in th
Ruby standard library
A template can be generated by running a piece of code written using th

object. A simple example is as shown below: require 'erb' x = 400 simple_template = "Value of x is: is <%= x %>." renderer = ERB.new(simple_template) puts output = renderer.result(binding) The result looks as follows: Value of x is: 400 The same could be achieved using the below code which does not make use of an ERB object: x = 400 string = "The value of x is: #" puts string Both of the above
code snippets Snippet is a programming term for a small region of re-usable source code, machine code, or text. Ordinarily, these are formally defined operative units to incorporate into larger programming modules. Snippet management is a feature of some text ...
generate the same output. But what happens when we interchange lines 2 with line 3 in the first code snippet and line 1 with line 2 in the second code snippet? The first snippet changes to the code shown below: require 'erb' simple_template = "Value of x is: is <%= x %>." x = 400 renderer = ERB.new(simple_template) puts output = renderer.result(binding) This still generates the same output. i.e., Value of x is: 400. The second code snippet changes to the below code: string = "The value of x is: #" x = 400 puts string The above code will not get executed. This is because the 1st line does not know the value of x when it gets executed. Thus, the main reason of using an ERB object is to write templates ahead of time, by ''binding'' variables and methods which may not exist at the given time. The template gets processed only when ''result'' is called on the ERB object. In order to get access to
instance method A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any o ...
s and
instance variable In class-based, object-oriented programming, an instance variable is a variable defined in a class (i.e. a member variable), for which each instantiated object of the class has a separate copy, or instance. An instance variable has similariti ...
of an object, ERB makes use of a ''binding'' object. Access to variables and methods of an object is given by the private ''binding'' object which exists in each ruby class. It is easy to get access to methods and variables within the method of a class. But to access variables of a different class, that class will have to expose its binding object via a public method. The example is as shown below: class ERBExample attr_accessor:variable1 # using bind to access class variables def render() renderer.result(binding) end def initialize(variable1) @variable1 = variable1 end # Expose private binding() method. def get_binding binding() end end example = ERBExample.new(variable1) renderer = ERB.new(template) puts output = renderer.result(example.get_binding) As we can see in the above example, we are exposing the ''binding'' object of the class ERBExample. Furthermore, we have used the ''binding'' object to access the variables and methods of the class within one of its methods.


new() method of ERB

The ''new'' method of the ERB object takes two more
parameters A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
. The second parameter specifies a safety level. By giving a number in the second parameter (max value = 4) one can make the template run in a different thread. The value of the number determines the safety level. At the maximum isolation level, unless the binding object is marked as trusted, ERB cannot use it. The third parameter specify optional modifiers. These can be used to control adding of newlines to the output. For example, to make sure that ERB does not output newlines after tag ends, we can create the ERB object as shown below renderer = ERB.new(template, 3, '>') To only provide the third parameter and ignore the second parameter, use 0 as the input for second parameter. ERB has many other methods exposed which can be used to render a template. For full list of APIs exposed by the ERB object, refer to th
ERB documentation
given in the reference section.


Running ERB from Command-line

As it has been already explained in the previous sections, the erb is used to generate templates. This is often used to generate web pages or other text files. Usually needs erb to push the output to his or her desired file. To achieve this, we can use the redirection ability provided in the
command-line A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
and redirect the output to a file rather than making it print on the standard output. erb sample1.erb.txt > my_view.html.erb In the above example, output gets redirected to ''my_view.html.erb'' file. Linking of third party libraries is achievable by making use of the -r option and providing the name of the library. To remember this functionality, one can remember the Ruby key word
require
', which does the same functionality as the -r option. The below example uses th

library. erb -r IPAddr sample1.txt.erb > my_view.html.erb As we have mentioned about the ''safety levels'' in the previous section, one can specify the safety level as a command line argument using the -S option erb -S 4 sample1.erb.txt > my_view.html.erb


erubis

'

'' is an implementation of eRuby implemented in Ruby and also in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's most ...
. According to its home page, it runs faster than eRuby and ERb and has several useful options, including alternate tags allowing for valid XML.


ember

'
ember
'' is a pure Ruby implementation of eRuby for
Linux Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which in ...
. It allows debugging of eRuby templates, improves their composability, and provides powerful shorthand eRuby directives.


Different implementation tags comparison

The below table compares the tags available in each of the above implementations


See also

*
mod_ruby mod_ruby is a module that embeds the Ruby interpreter into the Apache web server to allow Ruby code to execute natively, faster than other CGI methods. Its drawback is that the characteristic sharing of classes among Apache processes is not ...
*
Phusion Passenger Phusion Passenger (informally also known as mod_rails and mod_rack among the Ruby community) is a free web server and application server with support for Ruby, Python and Node.js. It is designed to integrate into the Apache HTTP Server or the ngin ...
(''mod_rails'') *
Haml Haml (HTML Abstraction Markup Language) is a templating system that is designed to avoid writing inline code in a web document and make the HTML cleaner. Haml gives the flexibility to have some dynamic content in HTML. Similar to other template s ...
*
RDoc RDoc, designed by Dave Thomas, is an embedded documentation generator for the Ruby programming language. It analyzes Ruby source code, generating a structured collection of pages for Ruby objects and methods. Code comments can be added in a ...
* Markaby


References


External links


ERB Library


a chapter fro
"The Pragmatic Programmer's Guide"

"web-mode.el"
emacs major mode for editing eRuby templates
ERB – Ruby Templating
{{Ruby programming language Template engines Ruby (programming language) Free computer libraries