我想以与 Devise 和 Sorcery 之类的插件公开方法相同的方式向我的控制器和视图公开一个current_user
方法。事实上,我正在搭载这个功能。然而,我试图为这个魔法猜想正确的语法并没有成功。这是我到目前为止所得到的......
# config/initializers/extra_stuff.rb
module ExtraStuff
class Engine < Rails::Engine
initializer "extend Controller with extra stuff" do |app|
ActionController::Base.send(:include, ExtraStuff::Controller)
ActionController::Base.helper_method :current_username
end
end
end
module ExtraStuff
module Controller
def self.included(klass)
klass.class_eval do
include InstanceMethods
end
end
module InstanceMethods
def current_username
current_user.username
end
end
end
end
当我尝试current_username
从控制器操作或视图调用时,我得到通常的未定义错误:
undefined local variable or method `current_username'
此方法的目的是特定于应用程序的,我不需要制作插件。我之所以提到这一点,是因为到目前为止我挖掘的参考资料仅从构建 Rails 引擎/插件的角度讨论了这个问题。当然,此时这正是我的代码所做的,但它仍然不起作用。oO
运行 Rails 4.2
更新Rails::Engine
:我能够通过上下移动东西来使功能正常工作。
module ExtraStuff
module Controller
def current_username
current_user.username
end
end
end
ActionController::Base.send(:include, ExtraStuff::Controller)
ActionController::Base.helper_method :current_username
但是我不明白为什么这甚至是必要的。Rails 引擎应该使用这些扩展来初始化ActionController::Base
. 我错过了什么?