instance method
helper
Ruby on Rails 2.3.18
Since v2.2.3 Last seen in v2.3.18Available in: v2.2.3 v2.3.18
Signature
helper(*args, &block)
The helper class method can take a series of helper module names, a block, or both.
-
*args: One or more modules, strings or symbols, or the special symbol:all. -
&block: A block defining helper methods.
Examples
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
When the argument is a module it will be included directly in the template class.
helper FooHelper # => includes FooHelper
When the argument is the symbol :all, the controller will include all helpers beneath ActionController::Base.helpers_dir (defaults to app/helpers/**/*.rb under RAILS_ROOT).
helper :all
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 }
Parameters
-
argsrest -
blockblock
Source
# File actionpack/lib/action_controller/helpers.rb, line 114
def helper(*args, &block)
args.flatten.each do |arg|
case arg
when Module
add_template_helper(arg)
when :all
helper(all_application_helpers)
when String, Symbol
file_name = arg.to_s.underscore + '_helper'
class_name = file_name.camelize
begin
require_dependency(file_name)
rescue LoadError => load_error
requiree = / -- (.*?)(\.rb)?$/.match(load_error.message).to_a[1]
if requiree == file_name
msg = "Missing helper file helpers/#{file_name}.rb"
raise LoadError.new(msg).copy_blame!(load_error)
else
raise
end
end
add_template_helper(class_name.constantize)
else
raise ArgumentError, "helper expects String, Symbol, or Module argument (was: #{args.inspect})"
end
end
# Evaluate block in template class if given.
master_helper_module.module_eval(&block) if block_given?
end
Defined in actionpack/lib/action_controller/helpers.rb line 114
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionController::Helpers::ClassMethods