Introduction to Embedded Ruby

This blog is for coders who have a basic understanding of Ruby on Rails.

What is Embedded Ruby?

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!

Resources:

Flatiron Software Engineering Student

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store