Ruby rails: helpers

From wikinotes
Revision as of 18:22, 19 April 2020 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Helpers are small, shared utility functions.
They are primarily used in views, but can also be used within controllers.

They are subclasses of ActionController::Base.

NOTE:

If helper :all exists in your application_controller.rb, then all helper-files/methods will be included in every view.



Documentation

builtin helper modules
(scroll to bottom)
https://api.rubyonrails.org/?q=ActionView::Helpers

Locations

{project}/app/helpers/application_helper.rb helpers available to entire application
{project}/app/helpers/{controller}_helper.rb helpers available to specific controller

Common Builtins

TODO:

What is the scope of these builtin helpers? All views? Controllers?

FormHelper

<%= form_tag(action='login') do %>
  <%= text_field_tag('username', @username) %>
  <%= text_field_tag('password', @password) %>
<% end %>

Custom Helpers

Helpers are automatically added to the scope of the view representing the same item.

You can add helpers to the controller, either using an include, or preferably, by accessing the method from the helpers attribute.

Custom helper

# {project}/app/helpers/user_helper.rb
module UsersHelper
  def get_username(user)
    user.first_name + user.last_name
  end
end
<!-- {project}/app/views/user/index.html.erb -->
Hello, <%= get_username() %>

Calling helper using helpers.method

Advantage of using this method is that it does not modify the namespace of your controller to include all helper methods.

# {project}/app/helpers/user_helper.rb
module UsersHelper
  def get_username(user)
    user.first_name + user.last_name
  end
end
# {project}/app/controllers/user_controller.rb
class UserController < ApplicationController
  def index
    @username = helpers.get_username()
  end
end