Module | AbstractController::Helpers::ClassMethods |
In: |
lib/abstract_controller/helpers.rb
|
Clears up all existing helpers in this class, only keeping the helper with the same name as this class.
The helper class method can take a series of helper module names, a block, or both.
When the argument is a module it will be included directly in the template class.
helper FooHelper # => includes FooHelper
When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file and include the module in the template class. The second form illustrates how to include custom helpers when working with namespaced controllers, or other cases where the file containing the helper definition is not in one of Rails’ standard load paths:
helper :foo # => requires 'foo_helper' and includes FooHelper helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper
Additionally, the helper class method can receive and evaluate a block, making the methods defined available to the template.
# One line helper { def hello() "Hello, world!" end } # Multi-line helper do def foo(bar) "#{bar} is the very best" end end
Finally, all the above styles can be mixed together, and the helper method can be invoked with a mix of symbols, strings, modules and blocks.
helper(:three, BlindHelper) { def mice() 'mice' end }
Declare a controller method as a helper. For example, the following makes the current_user controller method available to the view:
class ApplicationController < ActionController::Base helper_method :current_user, :logged_in? def current_user @current_user ||= User.find_by_id(session[:user]) end def logged_in? current_user != nil end end
In a view:
<% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>