Introduction to Embedded Ruby
This blog is for coders who have a basic understanding of Ruby on Rails.
What is Embedded Ruby?
Embedded Ruby a.k.a. ERB or eRuby is a template engine that embeds fragments of Ruby code into a text document. ERB is used in Ruby on Rails to show dynamic content on your website. The file extension for ERB is html.erb where you can write both HTML and Ruby code inside.
ERB tags:
Example Project:
In this example, we have a Blogs_controller.rb file that contains a BlogsController which inherits from the ApplicationController and has an index action. The index action has a @blogs instance variable that contains a list of all the blogs and will be accessible in the view. Click here to learn more about action controllers.
In the views/blogs folder, we have an Index.html.erb file that contains the code below:
In the code above, we are using the Ruby each method which will allow us to iterate over arrays and hashes. This method takes a block of code, and executes it once for each element in the array or hash. The first line of ERB tags will execute the each method on the instance variable taken from the index action in the BlogsController. The second line of ERB tags will render the results and display a list of each element on the webpage. The third line of ERB tags will terminate code block.
ERB is important because it can process the embedded Ruby in the backend before being sent off to a requesting web browser. Therefore, in the example above, what is actually being sent to the browser would look something like this:
What the webpage looks like:
Thank you for reading my blog!