コピペコードで快適生活

明日使えるソースを自分のために

prependでクラスメソッドを拡張する

singleton_classにprependすればOK。

class Hoge
  def self.hogehoge(*args)
    puts 'hogehoge'
  end
end

Hoge.hogehoge
# => hogehoge

Hoge.singleton_class.prepend Module.new {
  def hogehoge(*args)
    super(*args)
    puts 'extended hogehoge'
  end
}

Hoge.hogehoge
# => hogehoge
# => extended hogehoge

# 継承ツリー
Hoge.ancestors
# => [Hoge, Object, Kernel, BasicObject]
Hoge.singleton_class.ancestors
# => [#<Module:0x007fc15e090f70>, #<Class:Hoge>, #<Class:Object>, #<Class:BasicObject>, Class, Module, Object, Kernel, BasicObject]

class SomeClass
  class << self
    def some_classmethod
      "Hello"
    end
  end
end

SomeClass.some_classmethod
#=> Hello

singleton_class(特異クラス)とは、
すべてのオブジェクトが持つ自分だけの隠しクラスのこと。
インスタンスに独自に定義したメソッド(特異メソッド)は、
この特異クラスに定義しているという扱いらしい。

参考
https://qiita.com/ponoda/items/bfcf5533b532a6d32111
https://allabout.co.jp/gm/gc/453836/#note1