14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsのclass_methodsがやっていること

Posted at
module ModuleA
  extend ActiveSupport::Concern

  class_methods do
    def method_a
       puts "method_a"
    end
  end

end

class ClassA
  include ModuleA
end

ClassA.method_a #=> "method_a"

Moduleのメソッドをクラスメソッドとして使用できるようにするために、class_methodsを使う。
class_methodsで囲んだ箇所をActiveSupportのConcernがextendしてくれる。

class_methodsがないと‥

module ModuleA
  
  def method_a
     puts "method_a"
  end

end

class ClassA
  include ModuleA
end

ClassA.method_a #=> "NoMethodError: undefined method `method_a' for ClassA:Class"
instance_a = ClassA.new
instance_a.method_a #=> "method_a"

ModuleAのメソッドはClassAのインスタンスメソッドになる。

ちなみに

module ModuleA
  extend ActiveSupport::Concern

  class_methods do
    def self.method_a
      puts "self_method_a"
    end
  end
  
end

class ClassA
  include ModuleA
end

当たり前だが、ModuleAのself.method_aはあくまでもModuleAの特異メソッドだからClassAからもインスタンスからも呼び出すことはできない。

14
7
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
14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?