LoginSignup
0
0

【Ruby】モジュールでコールバックメソッドを定義する場合、included do内に記述する理由

Posted at

結論

  • コールバックメソッドは、実行するクラスのコンテキストで評価される必要がある。
  • モジュール内にそのまま記述すると、モジュールのコンテキストで評価されてしまう。
  • includedブロック内に記述することでコールバックメソッドがincludeしたクラスのコンテキストで評価されるから。

コールバックを定義するコード

  • difine_methodを使用して、実行時にメソッドを定義している
    • difine_methodが呼び出されるクラスに定義される
[:before, :after, :around].each do |callback|
        define_method "#{callback}_action" do |*names, &blk|
          _insert_callbacks(names, blk) do |name, options|
            set_callback(:process_action, callback, name, options)
          end
        end

        define_method "prepend_#{callback}_action" do |*names, &blk|
          _insert_callbacks(names, blk) do |name, options|
            set_callback(:process_action, callback, name, options.merge(prepend: true))
          end
        end

        # Skip a before, after or around callback. See _insert_callbacks
        # for details on the allowed parameters.
        define_method "skip_#{callback}_action" do |*names|
          _insert_callbacks(names) do |name, options|
            skip_callback(:process_action, callback, name, options)
          end
        end

        # *_action is the same as append_*_action
        alias_method :"append_#{callback}_action", :"#{callback}_action"
      end
    end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0