Ruby on Rails/ActionView/Custom Helpers

From Wikibooks, open books for an open world
< Ruby on Rails‎ | ActionView
Jump to: navigation, search

Custom Helpers[edit]

Rails comes with a wide variety of standard view helpers. Helpers provide a way of putting commonly used functionality into a method which can be called in the view. Helpers include functionality for rendering URLs, formatting text and numbers, building forms and much more.

Custom Helpers[edit]

Custom helpers for your application should be located in the app/helpers directory.

Application Helper[edit]

The file

app/helpers/application.rb

contains helpers which are available to all views.

Controller Helpers[edit]

By default other helpers are mixed into the views for based on the controller name. For example, if you have a ProjectsController then you would have a corresponding ProjectsHelper in the file

app/helpers/projects_helper.rb

Example[edit]

The following is an example of an Application Helper. The method title will be available to all views in the application. Methods added to this helper will be available to all templates in the application.

module ApplicationHelper
    def title
      t = 'My Site'
      t << ": #{@title}" if @title
      t
    end
  end