Ruby on Rails Interview Questions and Answers — Helpers — Part 3

Gokul
9 min readJun 9, 2024

--

  • How do you handle HTML and text formatting using Rails helper methods?
  • What is the purpose of the content_tag and tag helper methods in Rails views?
  • How can you generate image tags with helper methods in Rails?
  • What is the purpose of date and time helpers in Rails, and how do you use them?
  • How can you create custom helper methods to encapsulate common functionality in Rails views?

11. How do you handle HTML and text formatting using Rails helper methods?

Ruby on Rails provides various helper methods to handle HTML and text formatting efficiently and safely. Here are some key methods along with their usage:

sanitize and raw

sanitize: Cleans potentially harmful tags and attributes from HTML content.

<%= sanitize(@user_input) %>

raw: Marks a string as HTML safe, preventing it from being escaped. Use with caution.

<%= raw(@html_content) %>

content_tag

Generates HTML tags dynamically.

<%= content_tag(:div, "Hello, world!", class: "greeting") %>

tag

Generates both paired and self-closing HTML tags.

<%= tag.div class: "greeting", data: { toggle: "dropdown" } do %>
Hello, world!
<% end %>
<%= tag.img src: "path/to/image.jpg", alt: "My Image" %>

link_to

Creates HTML anchor tags for links.

<%= link_to "Click here", "https://example.com", class: "link" %>

simple_format

Converts plain text into HTML paragraphs, adding <br> tags for line breaks.

<%= simple_format(@user_text) %>

Number Formatting Helpers

number_to_currency: Formats numbers as currency

<%= number_to_currency(1500) %>

number_to_percentage: Formats numbers as percentages

<%= number_to_percentage(85, precision: 2) %>

number_to_human: Formats numbers in a human-readable format

<%= number_to_human(12345678) %>

Text Truncation and Excerpts

truncate: Shortens text to a specified length, adding an ellipsis

<%= truncate(@long_text, length: 100) %>

excerpt: Extracts an excerpt from text around a given phrase

<%= excerpt(@long_text, "keyword", radius: 50) %>

Pluralization and Singularization

pluralize: Automatically pluralizes words based on a given count

<%= pluralize(@comments.count, "comment") %>

singularize: Converts a plural word to its singular form

<%= "comments".singularize %>

Tag Stripping

strip_tags: Removes all HTML tags from a string

<%= strip_tags(@html_content) %>

strip_links: Removes all <a> tags from a string

<%= strip_links(@html_content_with_links) %>

Here’s an example demonstrating the use of these helpers in a Rails view:

<% @posts.each do |post| %>
<div class="post">
<h2><%= link_to post.title, post_path(post) %></h2>
<p><%= truncate(strip_tags(post.body), length: 150) %></p>
<p><%= pluralize(post.comments.count, "comment") %></p>
</div>
<% end %>

12. What is the purpose of the content_tag and tag helper methods in Rails views?

content_tag

The content_tag method is used to create an HTML tag with content inside it. It lets you specify the tag name, content, and HTML attributes, giving you control over its properties and contents.

Basic Usage

<%= content_tag(:div, "Hello, world!") %>

This generates:

<div>Hello, world!</div>

With HTML Attributes

<%= content_tag(:div, "Hello, world!", class: "greeting", id: "greeting-id") %>

This generates:

<div class="greeting" id="greeting-id">Hello, world!</div>

Nested Content

<%= content_tag(:div, class: "container") do %>
<%= content_tag(:p, "Paragraph inside div") %>
<% end %>

This generates:

<div class="container">
<p>Paragraph inside div</p>
</div>

tag

The tag method is similar to content_tag, but it is more flexible and can generate both paired and self-closing tags. It’s a recent addition to Rails and is designed to provide a more concise syntax for generating HTML tags.

Self-Closing Tags

<%= tag.br %>

This generates:

<br>
<%= tag.img src: "path/to/image.jpg", alt: "My Image" %>

This generates:

<img src="path/to/image.jpg" alt="My Image">

Paired Tags with Block Syntax

<%= tag.div class: "greeting" do %>
Hello, world!
<% end %>

This generates:

<div class="greeting">
Hello, world!
</div>

Attributes as Hashes

<%= tag.div class: "container", data: { toggle: "dropdown" } do %>
<p>Content inside container</p>
<% end %>

This generates:

<div class="container" data-toggle="dropdown">
<p>Content inside container</p>
</div>

Key Differences

  • Content: content_tag requires content to be provided (either as a parameter or a block), whereas tag can generate self-closing tags without content.
  • Syntax: tag often results in cleaner and more concise code, especially for self-closing tags.
  • Attributes: Both methods allow for the inclusion of HTML attributes but tag uses a hash syntax that can be more readable.

When to Use Which

  • Use content_tag: When you need to create tags with content inside them and prefer the explicitness of separating content from attributes.
  • Use tag: When you need to create self-closing tags or prefer a more concise syntax for both paired and self-closing tags.

Example Scenario

Suppose you need to create a form with input fields and a submit button dynamically:

<%= form_with url: "/submit", method: :post do %>
<%= tag.label for: "username" do %>
Username:
<% end %>
<%= tag.input type: "text", name: "username", id: "username" %>

<%= tag.label for: "password" do %>
Password:
<% end %>
<%= tag.input type: "password", name: "password", id: "password" %>

<%= tag.input type: "submit", value: "Submit" %>
<% end %>

In this example:

  • tag is used to create self-closing input tags.
  • tag with a block is used to create label tags with content.

By leveraging these helper methods, you can generate HTML dynamically in a clean and readable manner, making your views more maintainable and flexible.

13. How can you generate image tags with helper methods in Rails?

Basic Usage

The image_tag helper method is a convenient way to generate an HTML <img> tag in your Rails views. To use it, pass the filename of the image as an argument. Rails will automatically prepend the appropriate path based on your application's configuration.

<%= image_tag "example.jpg" %>

This generates the following HTML:

<img src="/assets/example.jpg" alt="Example">

Here, assumes that example.jpg is located in the app/assets/images directory. The alt attribute is automatically set to the base name of the image file (without the extension), which can be useful for accessibility purposes.

Specifying the Image Path

If your images are organized into subdirectories within app/assets/images, you can specify the relative path to the image:

<%= image_tag "subfolder/example.jpg" %>

This tells Rails to look for the image in app/assets/images/subfolder/, generating:

<img src="/assets/subfolder/example.jpg" alt="Example">

Adding HTML Attributes

You can customize the generated <img> tag by passing additional HTML attributes as options. This is particularly useful for adding CSS classes, setting the id, specifying a different alt text, and more:

<%= image_tag "example.jpg", alt: "An example image", class: "img-responsive", id: "example-image" %>

This generates the following HTML:

<img src="/assets/example.jpg" alt="An example image" class="img-responsive" id="example-image">

Using the Asset Pipeline

Rails uses the Asset Pipeline to manage and serve static assets like images, JavaScript, and CSS files. When using image_tag, you don't need to include the full path or file extension of the image if it follows a standard naming convention. For example:

<%= image_tag "example" %>

Rails will look for example.png, example.jpg, or example.gif in app/assets/images and generate:

<img src="/assets/example.png" alt="Example">

The Asset Pipeline also allows for versioning and digesting assets, which helps in cache busting and ensuring users get the most up-to-date files.

Internationalization (I18n) for Alt Text

To support multiple languages in your application, you can use Rails’ internationalization (I18n) features to set the alt attribute dynamically based on the user's locale. Define the translations in your locale files (e.g., config/locales/en.yml):

en:
images:
example_alt: "This is an example image"

Then, use the t method to retrieve the translation in your view:

<%= image_tag "example.jpg", alt: t('images.example_alt') %>

This generates:

<img src="/assets/example.jpg" alt="This is an example image">

Creating Custom Helper Methods

If you have recurring image tag configurations, you can create custom helper methods to encapsulate this logic, making your views cleaner and more maintainable. Define a custom helper method in a helper module (e.g., app/helpers/application_helper.rb):

module ApplicationHelper
def custom_image_tag(source, options = {})
options[:alt] ||= "Default alt text" # Set a default alt text if none is provided
options[:class] ||= "default-class" # Set a default CSS class if none is provided
image_tag(source, options)
end
end

With this helper in place, you can use custom_image_tag in your views:

<%= custom_image_tag "example.jpg" %>

This generates:

<img src="/assets/example.jpg" alt="Default alt text" class="default-class">

You can still override the default attributes by passing options:

<%= custom_image_tag "example.jpg", alt: "A custom alt text", class: "custom-class" %>

This generates:

<img src="/assets/example.jpg" alt="A custom alt text" class="custom-class">

14. What is the purpose of date and time helpers in Rails, and how do you use them?

Date and Time helpers in Rails are designed to make it easy to format, manipulate, and display date and time objects in your views. These helpers provide a convenient way to handle common date and time tasks such as formatting dates, displaying relative times (e.g., “2 days ago”), and selecting dates and times from forms.

Common Date and Time Helpers

Here are some of the most commonly used Date and Time helpers in Rails:

  1. distance_of_time_in_words
  2. time_ago_in_words
  3. datetime_select
  4. date_select
  5. time_select
  6. select_tag and related helpers

Let’s look at each of these in detail with examples.

distance_of_time_in_words

This helper calculates and returns the distance between two dates or times in words. It is useful for showing human-readable differences between two times.

<%= distance_of_time_in_words(Time.now, Time.now + 2.days) %>

This would display:

2 days

You can also include the include_seconds option to get more precise intervals:

<%= distance_of_time_in_words(Time.now, Time.now + 75.seconds, include_seconds: true) %>

This might display:

1 minute and 15 seconds

time_ago_in_words

This helper is a specific case of distance_of_time_in_words and is used to display the time difference from now to a given time. It's commonly used in social media applications to show how long ago something was posted.

<%= time_ago_in_words(3.days.ago) %>

This would display:

3 days ago

datetime_select

This helper creates a set of select boxes for year, month, day, hour, and minute, making it easy to input a full datetime value in a form.

<%= form_with model: @event do |f| %>
<%= f.label :start_time, "Start Time" %>
<%= f.datetime_select :start_time %>
<% end %>

This generates a series of select boxes for each component of the datetime.

date_select

Similar to datetime_select, this helper creates select boxes for the year, month, and day only, which is useful when you only need to capture a date without the time.

<%= form_with model: @event do |f| %>
<%= f.label :event_date, "Event Date" %>
<%= f.date_select :event_date %>
<% end %>

This generates select boxes for the date components.

time_select

This helper creates select boxes for hours and minutes, which is useful when you need to capture a time without a date.

<%= form_with model: @event do |f| %>
<%= f.label :start_time, "Start Time" %>
<%= f.time_select :start_time %>
<% end %>

This generates select boxes for the time components.

select_tag and Related Helpers

While not exclusively for dates and times, select_tag can be used to create custom date and time selectors when combined with Ruby's Date and Time classes.

<%= form_with model: @event do |f| %>
<%= f.label :event_month, "Event Month" %>
<%= f.select :event_month, options_for_select(Date::MONTHNAMES.compact.each_with_index.map { |month, i| [month, i + 1] }) %>
<% end %>

This creates a dropdown for selecting the month.

15. How can you create custom helper methods to encapsulate common functionality in Rails views?

Generate a Helper

Rails provides a generator to create a new helper file. Run the following command in your terminal:

rails generate helper <HelperName>

Replace <HelperName> with the name of your helper. For example, if you want a helper for common UI tasks, you might name it ui_helper:

rails generate helper ui

This command will create a file named ui_helper.rb in the app/helpers directory (app/helpers/ui_helper.rb).

Step 2: Define Helper Methods

Open the generated helper file (app/helpers/ui_helper.rb) and define your helper methods inside the module:

# app/helpers/ui_helper.rb
module UiHelper
def format_date(date)
date.strftime("%Y-%m-%d") if date.present?
end

def truncate_text(text, length = 30)
truncate(text, length: length)
end

# Define more helper methods as needed
end

In this example:

  • format_date: Formats a Date object into a string with the format "YYYY-MM-DD".
  • truncate_text: Truncates a given text to a specified length (default is 30 characters).

Step 3: Include Helper in Views (Optional)

By default, Rails automatically includes all helpers in all views. However, if you need to include the helper explicitly in a specific controller or view, you can use the helper method in your controller:

class ApplicationController < ActionController::Base
helper UiHelper
end

Or, in a specific controller:

class UsersController < ApplicationController
helper UiHelper
end

Step 4: Use Helper Methods in Views

You can now use your custom helper methods in any view file (*.html.erb, *.html.slim, etc.):

<!-- app/views/posts/show.html.erb -->
<h1><%= @post.title %></h1>
<p><%= format_date(@post.published_at) %></p>
<p><%= truncate_text(@post.body) %></p>

Step 5: Restart the Server (if necessary)

If you’ve just created a new helper file, you might need to restart your Rails server for it to pick up the changes.

Notes:

  • Naming Convention: Helper method names should represent their purpose and avoid conflicts with built-in or other helper methods.
  • Parameter Passing: Helper methods can accept parameters just like regular Ruby methods, allowing for flexibility in their usage.
  • Reusability: Encapsulating common functionality in helpers promotes DRY (Don’t Repeat Yourself) principles and keeps your views cleaner and more maintainable.

I appreciate you taking the time to read this. Please follow me on Medium and subscribe to receive access to exclusive content to keep in touch and continue the discussion. Happy Reading..!

--

--

Gokul

Consultant | Freelancer | Ruby on Rails | ReactJS