модуль AbstractController::Helpers::ClassMethods
Константы
- MissingHelperError
Публичные методы экземпляров
Очищает все существующие помощники в этом классе, оставляя только помощника с тем же именем, что и этот класс.
# File actionpack/lib/abstract_controller/helpers.rb, line 120
def clear_helpers
inherited_helper_methods = _helper_methods
self._helpers = Module.new
self._helper_methods = Array.new
inherited_helper_methods.each { |meth| helper_method meth }
default_helper_module! unless anonymous?
end Метод helper класса может принимать ряд имён модулей помощников, блок или и то, и другое.
Параметры
Если аргументом является модуль, он будет включён непосредственно в шаблонный класс.
helper FooHelper # => includes FooHelper
Если аргументом является строка или символ, метод добавит суффикс «_helper», загрузит файл и включит модуль в шаблонный класс. Второй вариант демонстрирует, как включать пользовательские помощники при работе с контроллерами с именованными пространствами имён или в других случаях, когда файл с определением помощника не находится в стандартных путях загрузки Rails:
helper :foo # => requires 'foo_helper' and includes FooHelper helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper
Кроме того, метод helper класса может принимать и обрабатывать блок, делая определённые методы доступными для шаблона.
# One line
helper { def hello() "Hello, world!" end }
# Multi-line
helper do
def foo(bar)
"#{bar} is the very best"
end
end
Наконец, все вышеперечисленные стили можно комбинировать, и метод helper может быть вызван с комбинацией symbols, strings, modules и блоков.
helper(:three, BlindHelper) { def mice() 'mice' end }
# File actionpack/lib/abstract_controller/helpers.rb, line 110
def helper(*args, &block)
modules_for_helpers(args).each do |mod|
add_template_helper(mod)
end
_helpers.module_eval(&block) if block_given?
end Объявляет метод контроллера как метод помощника. Например, следующее делает метод контроллера current_user доступным для представления:
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
В представлении:
<% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
Параметры
-
method[, method]- Имя или имена метода контроллера, которые должны быть доступны в представлении.
# File actionpack/lib/abstract_controller/helpers.rb, line 63
def helper_method(*meths)
meths.flatten!
self._helper_methods += meths
meths.each do |meth|
_helpers.class_eval " def #{meth}(*args, &blk) # def current_user(*args, &blk)
controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk)
end # end
", __FILE__, __LINE__ + 1
end
end При наследовании класса оберните его модуль помощника в новый модуль. Это гарантирует, что модуль родительского класса можно изменить независимо от дочернего класса.
# File actionpack/lib/abstract_controller/helpers.rb, line 36
def inherited(klass)
helpers = _helpers
klass._helpers = Module.new { include helpers }
klass.class_eval { default_helper_module! } unless klass.anonymous?
super
end Возвращает список модулей, нормализованных из допустимых типов помощников с следующим поведением:
а «foo_bar_helper.rb» загружается с помощью require_dependency.
- Модуль
-
Дополнительной обработки не требуется
После загрузки соответствующих файлов возвращаются соответствующие модули.
Параметры
-
args- Массив помощников
Возвращает
-
Array- Нормализованный список модулей для переданного списка помощников.
# File actionpack/lib/abstract_controller/helpers.rb, line 146
def modules_for_helpers(args)
args.flatten.map! do |arg|
case arg
when String, Symbol
file_name = "#{arg.to_s.underscore}_helper"
begin
require_dependency(file_name)
rescue LoadError => e
raise AbstractController::Helpers::MissingHelperError.new(e, file_name)
end
file_name.camelize.constantize
when Module
arg
else
raise ArgumentError, "helper must be a String, Symbol, or Module"
end
end
end
© 2004–2016 David Heinemeier Hansson
Licensed under the MIT License.