Ruby partials.
By: Jas Spencer
Tags: Rails, Partials, Programming, Ruby, Coding

The term ‘best practices’ gets thrown around a lot in every industry. As one goes through the early stages of their education in whatever they’re told that it is ‘best practice’ to do certain things one way as opposed to another. My issue with that is what might work great for someone might not work well for me, or you. Everyone has their own ‘best practices’ and I believe that it is up to the individual to determine that for themselves.

That being said, when it comes to coding, I believe one common best practice is to make sure any code you write should as clean and as easy to read as possible. If we look at coding through the lens of having a conversation with the computer (which it is) it would make sense to make that conversation easy and simple to follow and understand; similar to how a real conversation would work. In Ruby on Rails there is a tool called a partial which helps code be divided up and easily reused throughout any application.

Partial templates, or just partials, are a way to break up the rendering process into more manageable chunks as opposed to having all the code in a single file. Using partials to break up your code makes it easier to edit and debug should you need to do. No longer having to scan a seemingly endless page of code looking for a bug. The less code you have in a file, the easier it is to read, therefore editing and debugging comes easier.

When starting any new Rails project a file will generate called views/layouts/application.html.erb which might look something like this:

<!DOCTYPE html>

<html>

<head>

<title>Title Goes Here</title>

<%= csrf_meta_tags %>

<%= csp_meta_tag %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

</head> <body>

<%= yield %>

</body>

</html>

Adding any sort of HTML code to this will persist through the application. Often it is common to see the code for a navigation bar or footer go in this file.

For this example I want to add a navigation bar or ‘navbar’ so that users can freely move about the application. To build it, I used example code from Bootstrap for something that was already designed and styled:

<nav class="navbar navbar-expand-lg navbar-light bg-light">

<div class="container-fluid">

<a class="navbar-brand" href="#">Navbar</a>

<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav me-auto mb-2 mb-lg-0">

<li class="nav-item">

<a class="nav-link active" aria-current="page" href="#">Home</a>

</li>

<li class="nav-item">

<a class="nav-link" href="#">Link</a>

</li>

<li class="nav-item dropdown">

<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">

Dropdown

</a>

<ul class="dropdown-menu" aria-labelledby="navbarDropdown">

<li><a class="dropdown-item" href="#">Action</a></li>

<li><a class="dropdown-item" href="#">Another action</a></li>

<li><hr class="dropdown-divider"></li>

<li><a class="dropdown-item" href="#">Something else here</a></li>

</ul>

</li>

<li class="nav-item">

<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>

</li>

</ul>

<form class="d-flex">

<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">

<button class="btn btn-outline-success" type="submit">Search</button>

</form>

</div>

</div>

</nav>

This is a lot of code, and if I keep adding things like footers and such soon my file will be too cramped and clunky with code. If something came up that I was asked to change, I would have to comb through one gigantic file to fix or change something.

This is where partials come in. All partial templates begin with an underscore ‘_’ and then the name of the file, followed by “.html.erb” So in the layouts folder simply create a new file called:

_navbar.html.erb

In order to render any partial, simply replace all the navbar code with one line in views/layouts/application.html.erb with :

<%= render 'layouts/navbar' %>

That one line means tells the application.html.erb file to render all that navbar code! Like that our 30 or so lines of navbar code has been moved into its own file and we’ve reduced it down to one line!

Let’s take a look at another example. I’m building a Rails blog that allows users to write their own articles. As well as writing new ones, they can edit articles that they’re already written.

My form for creating a new article look like this:



<% if

<h2> The following errors prevented the article from being saved </h2>

<ul>

<%

<li><%= msg %></li>

<% end %>

</ul>

<% end %> Create a New Article @article .errors.any? %> The following errors prevented the article from being saved @article .errors.full_messages.each do |msg| %> <%= form_with scope: :article, url: articles_path , local: true do |f| %>

<p>

<%= f.label :title %><br />

<%= f.text_field :title %>

</p> <p>

<%= f.label :description %><br />

<%= f.text_area :description %>

</p> <p>

<%= f.submit %>

</p> <% end %>

The form for editing an article looks like this:



<% if

<h2> The following errors prevented the article from being saved </h2>

<ul>

<%

<li><%= msg %></li>

<% end %>

</ul>

<% end %> Edit Article @article .errors.any? %> The following errors prevented the article from being saved @article .errors.full_messages.each do |msg| %>

<p>

<%= f.label :title %><br />

<%= f.text_field :title %>

</p> @article , local: true) do |f| %>

<p>

<%= f.label :description %><br />

<%= f.text_area :description %>

</p> <p>

<%= f.submit %>

</p> <% end %>

These forms are nearly identical. In coding there is almost no point in writing the same thing twice so a partial can be used to clean this up.

First, the partial file is created:

_form.html.erb

Next all the code except for the h1 headings gets moved into the partial.

Finally, the New and Edit forms get the appropriate code to render the partial:

The updated New Article form looks like this:

<h1>Create a new article</h1>

<%= render 'form'%>

The updated Edit Article form looks like this:

<h1>Edit Article</h1>

<%= render 'form'%>

This is a great example showing how partials can make code reusable. In the long run this will lead to cleaner, easier to organize code.

Partials are a great tool in Rails to make code more manageable. They make debugging easier and can turn large chunks of code into reusable templates to avoid excessive coding. Code that is easy to read, edit, and change makes for one happy programmer.