2

以前はこのヘルパーが含まれていなかった拡張コントローラーに既存のヘルパーを追加する正しい方法を誰かが案内してくれますか?

たとえば、 timelog_controller_patch.rb で timelog_controller.rb コントローラーを拡張ました。次に、パッチで使用したいいくつかの機能をもたらすヘルパー Queriesを追加しようとしました。

パッチ (タイムログ拡張コントロール) にヘルパーを追加すると、常に同じエラーが発生します。

エラー:初期化されていない定数 Rails:: Plugin:: TimelogControllerPatch (NameError)

これが私が行った方法の例です:

module TimelogControllerPatch       
    def self.included(base)
        base.send(:include, InstanceMethods)
        base.class_eval do
          alias_method_chain :index, :filters
        end
    end
    module InstanceMethods
        # Here, I include helper like this (I've noticed how the other controllers do it)
        helper :queries
        include QueriesHelper

        def index_with_filters
            # ...
            # do stuff
            # ...
        end
    end # module
end # module patch

ただし、元のコントローラーに同じヘルパーを含めると、すべて正常に動作します (もちろん、これは正しい方法ではありません)。

誰かが私が間違っていることを教えてもらえますか?

前もって感謝します :)

4

2 に答える 2

4

メソッドは、helper正しく実行されていないモジュールに配置することにより、コントローラーのクラスで呼び出す必要があります。これはうまくいきます:

module TimelogControllerPatch       
    def self.included(base)
        base.send(:include, InstanceMethods)
        base.class_eval do
          alias_method_chain :index, :filters
          # 
          # Anything you type in here is just like typing directly in the core
          # source files and will be run when the controller class is loaded.
          # 
          helper :queries
          include QueriesHelper

        end
    end
    module InstanceMethods
        def index_with_filters
            # ...
            # do stuff
            # ...
        end
    end # module
end # module patch

Github で私のプラグインを自由に見てください。私のパッチのほとんどはlib/plugin_name/patches. ヘルパーを追加するものがあることは知っていますが、今は見つかりません。https://github.com/edavis10

PS パッチも必要とすることを忘れないでください。libプラグインのディレクトリにない場合は、相対パスを使用してください。

エリック・デイビス

于 2012-01-13T22:03:24.373 に答える
0

または、パッチを使用したくない場合は、次のようにします。

Rails.configuration.to_prepare do
  TimelogController.send(:helper, :queries)
end
于 2013-10-18T13:42:18.873 に答える