gpt4 book ai didi

ruby-on-rails - Rails 3.0 引擎 - 在 ActionController 中执行代码

转载 作者:行者123 更新时间:2023-12-04 16:56:23 26 4
gpt4 key购买 nike

我正在将我的 Rails 插件升级为可与最新 3.0RC1 版本一起使用的引擎,但我在找出扩展 ActionController 的最佳(也是最正确)方法时遇到了一些麻烦。 .我看过this post由 DHH 和 this question在这里,但我的问题更多是关于如何正确调用 ActionController 中的代码.

例如,我需要在我的引擎 Controller 中调用以下命令:

class ApplicationController < ActionController::Base
helper :all

before_filter :require_one_user
after_filter :store_location

private
def require_one_user
# Code goes here
end

def store_location
# Code goes here
end
end

我知道如何正确包含我的两个私有(private)函数,但我找不到让它正确调用 helper 的方法, before_filterafter_filter .

我将不胜感激一些链接或使这项工作的方法。我尝试将我的 Controller 命名为 ApplicationController 以外的其他名称并拥有真正的 ApplicationController扩展它,但这似乎也不起作用。我真的很喜欢任何让引擎用户的生活尽可能轻松的解决方案。理想情况下,他们不必扩展我的类(class),但他们会将所有功能都内置到他们自己的 ApplicationController 中。 .

最佳答案

您可能还想查看引擎子类中的初始化程序,因此您不必在 Controller 类中包含 View 助手。这将使您能够控制这些模块的加载顺序。

这是我一直在使用的:

module MyEngine
class Engine < Rails::Engine
initializer 'my_engine.helper' do |app|
ActionView::Base.send :include, MyEngineHelper
end

initializer 'my_engine.controller' do |app|
ActiveSupport.on_load(:action_controller) do
include MyEngineActionControllerExtension
end
end
end
end

此外, Action Controller 扩展的另一个选项是使用 mixin 模块。这将让您使用 before_filter、after_filter 等。

module MyEngineActionControllerExtension
def self.included(base)
base.send(:include, InstanceMethods)
base.before_filter :my_method_1
base.after_filter :my_method_2
end

module InstanceMethods
#...........
end
end

另一件事......如果您在 gem 的顶层创建默认的 rails 目录,您不必担心需要帮助程序或 Controller 。您的引擎子类可以访问它们。所以我在这里添加我的应用程序 Controller 和应用程序助手扩展:

/myengine/app/helpers/myengine_application_helper_extension.rb
/myengine/app/controllers/my_engine_action_controller_extension.rb

我喜欢这个设置,因为它看起来类似于您的 rails 应用程序中的 application_controller 和 application_helper。同样,这只是个人喜好,但我尽量保留与 Rails 直接相关的任何内容,例如/my_engine/app 中的 Controller 、助手和模型,以及/my_engine/lib 中通常与插件相关的任何内容

查看 Jose Valim 的本教程,了解有关初始化程序的更多信息:
https://gist.github.com/e139fa787aa882c0aa9c (engine_name 现在已弃用,但该文档的大部分内容似乎都是最新的)

关于ruby-on-rails - Rails 3.0 引擎 - 在 ActionController 中执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3468858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com