Ruby 模块 - 包括 do end 块 [英] Ruby modules - included do end block

查看:41
本文介绍了Ruby 模块 - 包括 do end 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个模块MyModule:

module MyModule

  extend ActiveSupport::Concern

  def first_method
  end

  def second_method
  end

  included do
    second_class_method
  end

  module ClassMethods
    def first_class_method
    end

    def second_class_method
    end
  end
end

当某个类includes这个模块时,它将有2个方法公开为实例方法(first_methodsecond_method)和2个类方法(first_class_methodsecond_class_method) - 很清楚.

When some class includes this module, it will have 2 methods exposed as instance methods (first_method and second_method) and 2 class methods (first_class_method and second_class_method) - it is clear.

据说,

included 块将在类的上下文中执行包括模块.

included block will be executed within the context of the class that is including the module.

具体是什么意思?意思是,这个方法(second_class_method)到底什么时候执行?

What does it mean exactly? Meaning, when exactly would this method (second_class_method) be executed?

推荐答案

这是一个实际的例子.

class MyClass
  include MyModule
end

当您将模块包含在类中时,将调用 included 钩子.因此,second_class_method会在Class的范围内被调用.

When you will include the module in a class, the included hook will be called. Therefore, second_class_method will be called within the scope of Class.

这里发生了什么

  1. first_methodsecond_method 作为 MyClass 的实例方法被包含进来.

instance = MyClass.new
instance.first_method
# => whatever returned value of first_method is

  • ClassMethods 的方法会自动混合为 MyClass 的类方法.这是一个常见的 Ruby 模式,由 ActiveSupport::Concern 封装.非 Rails Ruby 代码是

  • The methods of ClassMethods are automatically mixed as class methods of MyClass. This is a common Ruby pattern, that ActiveSupport::Concern encapsulates. The non-Rails Ruby code is

    module MyModule
      def self.included(base)
        base.extend ClassMethods
      end
    
      module ClassMethods
        def this_is_a_class_method
        end
      end
    end
    

    结果

    MyClass.this_is_a_class_method
    

    或者你的情况

    MyClass.first_class_method
    

  • included 是一个对以下代码有效的钩子

  • included is a hook that is effectively to the following code

    # non-Rails version
    module MyModule
      def self.included(base)
        base.class_eval do
          # somecode
        end
      end
    end
    
    # Rails version with ActiveSupport::Concerns
    module MyModule
      included do
        # somecode
      end
    end
    

    它主要是常见模式的语法糖".在实践中发生的情况是,当您混合模块时,该代码在混合器类的上下文中执行.

    It's mostly "syntactic sugar" for common patterns. What happens in practice, is that when you mix the module, that code is executed in the context of the mixer class.

    这篇关于Ruby 模块 - 包括 do end 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆