您的模块不会自动加载(至少在 3.2.6 中不会)。您必须显式加载它。您可以通过以下代码行来实现此目的
# in application.rb
config.autoload_paths += %W(#{config.root}/lib)
您可以使用以下命令检查自动加载路径Rails.application.config.autoload_paths
。也许它确实是为你定义的?
现在您确定您的模块已加载,您可以签入它rails console
通过致电
> Functions::FormHelper
现在默认情况下您不能将该模块用作视图助手。使用#included
当您的模块被包含时定义助手。这样你就实现了“惰性评估”。我认为你的代码的问题在于helper
方法在模块被包含之前被调用。 (如果我错了,应该有人纠正我)
这是代码:
Module Functions
Module FormManager
def error_message() ...
end
def self.included m
return unless m < ActionController::Base
m.helper_method :error_message
end
end
end
您还应该删除helper
来自控制器的线路。
EDIT:
您无需自动加载即可实现此目的。只需使用require "functions/form_manager"
。您为每个方法定义一个 helper_method 。如果您希望使用所有模块方法作为助手使用
def self.included m
return unless m < ActionController::Base
m.helper_method self.instance_methods
end
EDIT2:
看来你不需要使用self.included
。这实现了相同的功能:
class ApplicationController < ActionController::Base
include Functions::FormManager
helper_method Functions::FormManager.instance_methods
end