Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Use Rails Helpers (Complete Guide)

What are Helpers in Rails?

A Helper is a method that is (mostly) used in your Rails views to extract reusable code. Rails comes with a set of useful built-in helper methods.

One of these built-in helpers is time_ago_in_words.

Here’s an example:

time_ago_in_words(Time.now)
# "less than a minute"

time_ago_in_words(Time.now + 60)
# "1 minute"

time_ago_in_words(Time.now + 600)
# "10 minutes"

This method is helpful whenever you want to display time in this specific format.

Another Rails view helper is number_to_human.

Example:

number_to_human(10_000)
# "10 Thousand"

This is great when you want to take a number & print it as you would read it, which makes it feel more human.

You can find more helpers in the Ruby on Rails documentation.

But did you know you can write your own?

Writing Your Own Helper Methods

If you’re looking to write custom helper methods, the correct directory path is app/helpers.

You write your helpers inside a helper module.

Every Rails application comes with a base helper module by default, it’s called ApplicationHelper.

Here’s where you can add your helper methods.

These methods become available to all your views automatically. Later you’ll learn how to use them in controllers & why that may be a bad idea.

You could write all your helpers in ApplicationHelper.

But there is another option…

You can create helper modules so you can better organize your methods.

Instructions:

  • Create a new file under app/helpers
  • Name it something like user_helper.rb
  • Add a new module which matches the file name

Example:

# app/helpers/user_helper.rb

module UserHelper
  def format_name(user)
    if user.gender == "M"
      "Mr. #{user.name}"
    else
      "Ms. #{user.name}"
    end
  end
end

This code can be used to address a person in a formal way based on their gender.

The main benefit?

You don’t have to repeat this logic in other views when you need it & when you need to change the code… it only has to change in one place.

Very nice!

Using Your New Helper Module

You can use your helper methods in your views.

Like this:


Easy, right?

If you want to use helpers outside of views you’ll need something else.

How to Use Helpers From Controllers

It’s possible, although not very common, to use helper methods from controller actions.

Before Rails 5, you had to include the helper module.

In newer versions, you can use helpers in your controller with the helpers (plural) object.

Like this:

class UsersController
  def index
    helpers.time_ago_in_words(Time.now)
  end
end

This way you can use helpers from your controller. But think twice before doing this because it may be a design issue.

Consider using a plain Ruby object instead.

Fun With The Rails Console

I love using the Rails console (irb with your Rails app loaded) to try out methods & play around with things.

Helpers included!

You can use helpers from the console with helper.method_name.

Notice the singular form of “helper” so you don’t get an error message. And remember that the console doesn’t reload code changes automatically.

Best Practices for Writing Rails View Helpers

When should you create a helper method?

Whenever you have logic that produces bits of HTML.

Usually, this falls into one of two categories, one is string formatting & the other is conditional page elements.

Another tip…

If you want to write good helpers don’t use any instance variables, they may be available in your current view, but they may not be in another view.

That will result in an error because of missing variables.

The solution?

Use parameters, so any data your method needs is clear & explicit.

# wrong way

def eat_healthy
  @fruit.eat
end

# do this instead

def eat_healthy(fruit)
  fruit.eat
end

My final tip is to divide your helpers into modules, where each module name describes clearly what kind of methods it contains.

However:

This won’t help with duplicated method names, which can result in errors & confusion.

All your helpers should have unique names.

Summary

You have learned about helpers in Rails! A set of utility methods you can use for formatting & handling complex logic in your views.

Now it’s time to create your own helpers.

Thanks for reading

The post How to Use Rails Helpers (Complete Guide) appeared first on RubyGuides. Don't miss your free gift here :)



This post first appeared on Black Bytes, please read the originial post: here

Share the post

How to Use Rails Helpers (Complete Guide)

×

Subscribe to Black Bytes

Get updates delivered right to your inbox!

Thank you for your subscription

×