ERuby

Last updated
eRuby
Other namesERB
Repository github.com/ruby/erb
Written in Ruby
Type Template engine
License BSD 2-Clause License

Embedded Ruby (also shortened as ERB) is a templating system that embeds Ruby into a text document. It is often used to embed Ruby code in an HTML document, similar to ASP and JSP, and PHP 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. [1]

Contents

The View module of Ruby on Rails is responsible for displaying the response or output on a browser. In its simplest form, a view can be a piece of HTML 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. [2]

Usage

eRuby allows Ruby code to be embedded within a pair of <% and %> delimiters. 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 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:

  1. Expression tags
  2. Execution tags
  3. Comment tags [3]

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. During the rendering of the template, 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=500template=ERB.new("The value of x is: <%= x %>")putstemplate.result(binding)

The resulting text looks like this: The value of x is: 500 [1]

Execution tags

<%%> : Code enclosed in such tags is called as a scriptlet. 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]

<ul><%4.timesdo%><li>list item</li><%end%></ul>

In the above example, the text list item gets printed four times. The scriptlet 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: [5]

<%# 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 #{string_name}, which is similar in languages such as Perl or PHP.

Newlines in eRuby can be suppressed by adding a hyphen at the beginning of the end tag delimiter. For example:

<%2.timesdo-%><%=@name%><%end-%>

In the output of the above code, the value of name gets printed twice in the same line. [1] [3]

Implementations

There are several implementations of eRuby, namely:

  1. ERB
  2. erubis
  3. ember

erb

erb is an implementation of eRuby written purely in the Ruby programming language and included in the Ruby standard library. [2]

A template can be generated by running a piece of code written using the ERB object. A simple example is as shown below:

require'erb'x=400simple_template="Value of x is: is <%= x %>."renderer=ERB.new(simple_template)putsoutput=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=400string="The value of x is: #{x}"putsstring

Both of the above code snippets 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=400renderer=ERB.new(simple_template)putsoutput=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}"x=400putsstring

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 methods and instance variable 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: [2] [4]

classERBExampleattr_accessor:variable1# using bind to access class variablesdefrender()renderer.result(binding)enddefinitialize(variable1)@variable1=variable1end# Expose private binding() method.defget_bindingbinding()endendexample=ERBExample.new(variable1)renderer=ERB.new(template)putsoutput=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. 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 [3] [4]

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 the 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 and redirect the output to a file rather than making it print on the standard output. [3]

erbsample1.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 the IPAddr library.

erb-rIPAddrsample1.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 [3]

erb-S4sample1.erb.txt>my_view.html.erb 

erubis

erubis is an implementation of eRuby implemented in Ruby and also in Java. 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. 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 [4] [6] [7]

Implementations
Simple expression tag
<%=%>
Simple execution tag
<%%>
Simple comment tag
<%#%>
Ability to configure tag patternShort hand notation for tags<%~%><%+%><%<><%|>
erb
YesYesYesNoYes, <%xy%> can be written as %xy.NoNoNoNo
erubis
YesYesYesYes, can change tag pattern to anything.

ex - [% %] etc.

Yes,

as one can change tag patterns.

NoNoNoNo
ember
YesYesYesNoYes, <%xy%> can be written as %xy.The content of the tag is evaluated as an eRuby template.The content of the tag is evaluated as Ruby code and is expected to be a path pointing to a Ruby template file which is read, evaluated, and rendered.Same as <%+%> but file contents are simply rendered into the output.Treats the enclosed code as a block of Ruby code and (if necessary) appends a do keyword to the body of the tag.

See also

Related Research Articles

<span class="mw-page-title-main">Common Lisp</span> Programming language standard

Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ANSI INCITS 226-1994 (S2018). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived from the ANSI Common Lisp standard.

Jakarta Server Pages is a collection of technologies that helps software developers create dynamically generated web pages based on HTML, XML, SOAP, or other document types. Released in 1999 by Sun Microsystems, JSP is similar to PHP and ASP, but uses the Java programming language.

A string literal or anonymous string is a literal for a string value in the source code of a computer program. Modern programming languages commonly use a quoted sequence of characters, formally "bracketed delimiters", as in x = "foo", where "foo" is a string literal with value foo. Methods such as escape sequences can be used to avoid the problem of delimiter collision and allow the delimiters to be embedded in a string. There are many alternate notations for specifying string literals especially in complicated cases. The exact notation depends on the programming language in question. Nevertheless, there are general guidelines that most modern programming languages follow.

In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in the definition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.

In some programming languages, eval, short for the English evaluate, is a function which evaluates a string as though it were an expression in the language, and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval. The input to eval is not necessarily a string; it may be structured representation of code, such as an abstract syntax tree, or of special type such as code. The analog for a statement is exec, which executes a string as if it were a statement; in some languages, such as Python, both are present, while in other languages only one of either eval or exec is.

RubyCocoa is a macOS framework that provides a bridge between the Ruby and the Objective-C programming languages, allowing the user to manipulate Objective-C objects from Ruby, and vice versa. It makes it possible to write a Cocoa application completely in Ruby as well as to write an application that mixes Ruby and Objective-C code. An Apple project called MacRuby was under development to replace RubyCocoa in 2008. A proprietary spin-off called RubyMotion was subsequently released in 2012, available for iOS, macOS and Android.

In class-based, object-oriented programming, a constructor is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

Javadoc is a documentation generator created by Sun Microsystems for the Java language for generating API documentation in HTML format from Java source code. The HTML format is used for adding the convenience of being able to hyperlink related documents together.

In computing, a here document is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also used for a form of multiline string literals that use similar syntax, preserving line breaks and other whitespace in the text.

C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

<span class="mw-page-title-main">Snippet (programming)</span> Small region of re-usable source code, machine code, or text

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 editors, program source code editors, IDEs, and related software. It allows the user to avoid repetitive typing in the course of routine edit operations.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". The aspect compile-time type safety was not fully achieved, since it was shown in 2016 that it is not guaranteed in all cases.

Haml is a templating system that is designed to avoid writing inline code in a web document and make the HTML cleaner. Haml gives you the flexibility to have some dynamic content in HTML. Similar to other template systems like eRuby, Haml also embeds some code that gets executed during runtime and generates HTML code in order to provide some dynamic content. In order to run Haml code, files need to have a .haml extension. These files are similar to .erb or .eRuby files, which also help embed Ruby code while developing a web application.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

Mustache is a web template system. Mustache is described as a logic-less system because it lacks any explicit control flow statements, like if and else conditionals or for loops; however, both looping and conditional evaluation can be achieved using section tags processing lists and anonymous functions (lambdas). It is named "Mustache" because of heavy use of braces, { }, that resemble a sideways moustache. Mustache is used mainly for mobile and web applications.

<span class="mw-page-title-main">Yesod (web framework)</span>

Yesod is a web framework based on the programming language Haskell for productive development of type-safe, representational state transfer (REST) model based, high performance web applications, developed by Michael Snoyman, et al. It is free and open-source software released under an MIT License.

The syntax of the Ruby programming language is broadly similar to that of Perl and Python. Class and method definitions are signaled by keywords, whereas code blocks can be defined by either keywords or braces. In contrast to Perl, variables are not obligatorily prefixed with a sigil. When used, the sigil changes the semantics of scope of the variable. For practical purposes there is no distinction between expressions and statements. Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Unlike Python, indentation is not significant.

References

  1. 1 2 3 Brown, Gregory (2009). Ruby Best Practices . O'Reilly. pp.  279–281. ISBN   978-0596523008.
  2. 1 2 3 S., Ruby; D., Thomas; Hansson D, Heinemeier (2011). Agile Web Development with Rails. The Pragmatic Programmers. p. 35. ISBN   978-1-934356-54-8.
  3. 1 2 3 4 5 Ellis, Stuart (1 July 2016). "An Introduction to ERB Templating" . Retrieved 12 September 2016.
  4. 1 2 3 4 "ERB". 23 February 2015. Retrieved 12 September 2016.
  5. "ERB – Ruby Templating". 2016. Retrieved 12 September 2016.
  6. "ember(1)". 29 June 2011. Retrieved 12 September 2016.
  7. "Erubis". 2011. Archived from the original on 27 March 2017. Retrieved 12 September 2016.