0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsのclass_methodsってなに?

Last updated at Posted at 2025-05-31

はじめに

railsのソースコードの中で簡単そうなメソッドを探していたら、class_methodsを見つけました。深ぼってみたら、今後の開発に活かしたいと持ったのでその備忘録です。

使い方

class_methods はモジュールのメソッドを、include先のクラスのクラスメソッドとして使ってねという指示。

module MyFeature
  extend ActiveSupport::Concern

  class_methods do
    def greet
      puts "こんにちは"
    end
  end
end

class User
  include MyFeature
end

User.greet  # => こんにちは

これ、普通に def self.greet で書けばよくない?とおもったのですが、

module MyFeature
  def self.greet
    puts "こんにちは"
  end
end

class User
  include MyFeature
end

User.greet  # => ❌ エラーになる!

self.greetしたらモジュール自身のメソッドとなり引用先のクラスには渡らない。このように、class_methods を使うことで、モジュールの機能をクラスに自然に拡張できるのが特徴です。

まとめ

  • def self.xxx はモジュール自身のメソッドになるので、include先のクラスには渡らない
  • class_methods do ... end を使うことで、include先のクラスにクラスメソッドを自然に追加できる
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?