модуль AbstractController::Helpers::ClassMethods
Публичные методы экземпляра
# File actionpack/lib/abstract_controller/helpers.rb, line 117
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 Очищает все существующие помощники в этом классе, сохраняя только помощника с тем же именем, что и у этого класса.
# File actionpack/lib/abstract_controller/helpers.rb, line 107
def helper(*args, &block)
modules_for_helpers(args).each do |mod|
add_template_helper(mod)
end
_helpers.module_eval(&block) if block_given?
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 60
def helper_method(*meths)
meths.flatten!
self._helper_methods += meths
meths.each do |meth|
_helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
def #{meth}(*args, &blk) # def current_user(*args, &blk)
controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk)
end # end
ruby_eval
end
end Объявляет метод контроллера как помощника. Например, следующая команда делает методы контроллера current_user и logged_in? доступными для представления:
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 32
def inherited(klass)
helpers = _helpers
klass._helpers = Module.new { include helpers }
klass.class_eval { default_helper_module! } unless klass.anonymous?
super
end При наследовании класса, обертывает его модуль помощников в новый модуль. Это гарантирует, что модуль родительского класса можно изменять независимо от дочернего класса.
# File actionpack/lib/abstract_controller/helpers.rb, line 143
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
mod_name = file_name.camelize
begin
mod_name.constantize
rescue LoadError
# dependencies.rb gives a similar error message but its wording is
# not as clear because it mentions autoloading. To the user all it
# matters is that a helper module couldn't be loaded, autoloading
# is an internal mechanism that should not leak.
raise NameError, "Couldn't find #{mod_name}, expected it to be defined in helpers/#{file_name}.rb"
end
when Module
arg
else
raise ArgumentError, "helper must be a String, Symbol, or Module"
end
end
end Возвращает список модулей, нормализованных из приемлемых типов помощников с таким поведением:
а “foo_bar_helper.rb” загружается с помощью require_dependency.
- Модуль
-
Дальнейшая обработка не требуется
После загрузки соответствующих файлов возвращаются соответствующие модули.
Параметры
-
args- Массив помощников
Возвращаемое значение
-
Array- Нормализованный список модулей для списка предоставленных помощников.
© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.