How to Develop Lightweight Components Using Ruby on Rails Helpers and Stimulus

Ruby on Rails

Rails is an open-source web development framework initially introduced in 2004 and written in Ruby language. Ruby on Rails which is also commonly known as Rails, is considered a server-side web application framework. Also, it has limited restrictions and high compatibility because of having MIT License. Moreover, it is a model-view-controller framework that helps in providing default structures to support databases, web services, and web pages. The purpose of this open-source software is to help create more accessible programming web applications of any complexity. Ruby on Rails uses practices like JSON or XML for transferring data and HTML, CSS, and JavaScript for the user interface.

Lightweight Components

A component that borrows the screen resource of its ancestor and does not possess a native resource of its own is known as the lightweight component. These components use the resources efficiently. As a result, these are relatively more consistent while being used in cross-platform developments. In addition, the developers prefer lightweight components because they help shape the implementation by customization and provide them a cleaner look-and-feel integration.

Helpers and Stimulus

Helpers

The helpers are the methods available to the developers to use in their rails view and share their reusable code. There are numerous helpers available in the Ruby on Rails framework, which help work with various components such as assets, dates, forms, numbers, and model objects. In addition, there is an option to use built-in helpers as well as customize them. By default, each controller contains all helpers. These included helpers are accessible on the controller through the keyword “helpers.”

Stimulus

Stimulus is a framework of JavaScript that has modest ambitions. Its primary purpose is to add to the HTML to make it more efficient, enhanced, and reliable. It generally works on four main concepts:

1. Controllers

As the primary purpose of the stimulus is to connect the DOM HTML elements with the javascript to provide customization options, controllers are generally the instances of the javascript classes that the users define in their application. Therefore, every controller in the application has a link to an HTML element in the DOM.

2. Life Cycle Callback

The methods that allow the developers to respond to the controllers’ connection and disconnection to or from the document are called life cycle callbacks. These are the primary callback methods used inside the controller class:

  1. initialize()
  2. connect()
  3. disconnect()

3. Actions

The actions define that how the controllers will manage the DOM events. For instance, the developer may want to invoke some function or change the HTML element properties when a user clicks on a specific button on the user interface. So, in this scenario, he will write the function call or property change code inside the controller, which will extend the controller class, and the action will be “OnClick” of that particular button.

4. Targets

The developers can refer to the elements by their names using target. They need to define the targets inside their controller functions and assign them to the element using the target attribute.

It is important to note that this framework does not come with the application automatically, and the user needs to install and import stimulus to use it in his application.

Building Lightweight Components using Helpers and Stimulus

The developers do not give much attention to the customized assistants used in rails during development. However, these customized assistants help develop lightweight components and reduce the overlap of the stimulus controllers. In addition, the stimulus can help in identifying the functionality by analyzing the markup attributes. Moreover, the components having various values and actions can hide some underlying implementation details according to the developer’s needs.

Example

Following is a simple example of hovercard controller usage. It is a sample of two actions to be used that are showing and hiding the card on hover. Following is a code for such example:

<div class=” inline-block” data-controller=” hovercard” data-hovercard-url-value=” <%=hovercard-shoe-path(shoe)%>” data-action=” mouseenter->hovercard#show mouseleave->hovercard#hide”> 
<%=link-to shoe.name, shoe, class: “branded-link” %>
</div>

Here the hovercard-controller must be passed in a URL value and have actions to show and hide the card on hover. The above coding example is wrapping this particular controller around a link. This wrapping makes it easy to be styled and open for customization for every type of hovercard the user needs in the application. Additionally, the users can add the customized

Rails helper, which allows them to utilize this controller for other types of hover cards.

Use in Views

The modules available in the “helpers” folder are automatically available for the developer to use in the views. Following is an example of this consideration:

module HovercardHelper
def hovercard (url, &block)
content-tag (: div, “data-controller”: “hovercard”, “data-hovercard-url-value”: url,
“data-action”: “mouseenter->hovercard#show mouseleave->hovercard#hide”, &block) end def repo_hovercard(repo, &block) hovercard hovercard_repository_path(repo), &block end
def user_hovercard(user, &block) hovercard hovercard_user_path(user), &block end end

Customize Components

The helpers in Ruby on Rails provide assistance in creating customized components for the abstraction of implementation details. The Ruby Blocks are used to create flexible components in Ruby on Rails. The Ruby Block is a technology of putting statements in a group form adjacent to a method call. It helps in customizing the code as per the developer’s need.

Following is an example of this:

<%= user_hovercard(@user) do %>
<%= link_to @user.username, @user %>
<% end %>
<%= repo-hovercard(repository) do %>
<div class=” flex items-center space-x-2”>
<svg></svg>
<%= link_to repository.name, repository %>
</div>
<% end %>

The above code is an example of building a repo-hovercard helper, which takes a Repository model and a block to render in the method’s argument. It allows a complete hold of displaying on the page based on the page context. Moreover, it is also beneficial to change the stimulus controller in one spot rather than have it scattered across various views in the application.

Create Helpers Modules

The users can also write their helpers inside the app/helpers directory instead of using the already available methods to create their components. First, the users need to write the code inside the helper module. It then becomes accessible to all the application views automatically. Each application in ruby on rails contains a default helper module, called ApplicationHelper, in which the developers can write their method or choose to create their helper modules for better organization of their methods.

Instructions

The user needs to follow these steps to create his helper module:

  1. First, find and move to the directory named app/helpers.
  2. Create a file inside it with the ‘.rb’ extension, such as my-helper-module.rb.
  3. Create a module inside the file with the same name as the file name.

Example

Following is the sample example of a module:

module my-helper-module
def format_position (professor)
If professor.qualification == “PhD”
“Dr. #{professor.name}” else
“Sir. #{professor.name}” end end

Explanation

The above module checks the qualification of a college professor to assign honorifics to them.

Additionally, it is common to refer to the professors as “Sir” and Ph.D. professors as “Doctor.” The above function does the same for the professor in application views. The primary benefit of this module is that the user can now call it anywhere in the application, wherever he wants to refer to the professors.