开发者

Modules in Ruby

开发者 https://www.devze.com 2023-03-11 02:44 出处:网络
Please explain why self is used in def self.included (klass) below. module A def self.included(klass) puts \"A -> #{klass}\"

Please explain why self is used in def self.included (klass) below.

module A
  def self.included(klass)
    puts "A -> #{klass}"
    puts A
    puts self
  end
end

class X
  include开发者_如何学JAVA A
end


By writing def self.included you are defining a method that is part of the singleton class of module A. In general, singleton methods can only be called by doing A.included() but this singleton method has a special name included that causes the Ruby interpreter to call when the module gets included in to a class.

A normal method in a module (defined with def foo) can only be called if the module gets included in to something else.


This is how you declare a module method that can be called directly. Normally methods defined within a module are only usable if another class or module includes them, like class X in this example.

module Example
  def self.can_be_called
    true
  end

  def must_be_included
    true
  end
end

In this case you will see these results:

Example.can_be_called
# => true

Example.must_be_included
# => NoMethodError: undefined method `must_be_included' for Example:Module

The self declared methods are not merged in to the classes or modules that include it, though. They are special-purpose that way.

0

精彩评论

暂无评论...
验证码 换一张
取 消