LoginSignup
0
1

More than 5 years have passed since last update.

Moduleについて

Posted at

いつもmoduleの動きぐぐってるのでメモ

Moduleとは

  • classとほぼ同じ。classとの違いはインスタンス生成できないところ。

動作確認

インスタンスメソッドをmoduleに定義。classでincludeして使う。


# Moduleをincludeしたときに、特異クラスが自動生成されメソッドが定義されることの確認
module InsModule
  def instance_method
    p 'instance_method'
  end
end

class MyClass
  include InsModule
end

# moduleのメソッド呼べる
b = MyClass.new
b.instance_method
# => "instance_method"

# 特異クラスにinstance_method定義されていると思ったけど、されてない??謎
p MyClass.singleton_class.instance_methods(false)
# => []

クラスメソッド風をmoduleに定義。classでincludeして使う。


# moduleに特異メソッドを定義すると、includeしたクラスからクラスメソッド風に呼べることの確認
module ClsModule
  # self.includedはincludeした時に呼ばれる
  def self.included(base)
  # extendは、baseオブジェクトの特異クラスにモジュールを取り込み、モジュールのメソッドを特異メソッドとして使えるようにする
    base.extend(ClassMethods)
  end
# ↑ここはextend ActiveSupport::Concernで書き換えるのが主流っぽい

  module ClassMethods
    def class_method
      p 'class_method'
    end
  end
end

class MyClass
  include ClsModule
end

MyClass.class_method
# => class_method
0
1
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
1