0
0

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 3 years have passed since last update.

Refinementでクラスメソッドを再定義する

Posted at

方法1

singleton_classを使う

class MyClass
  def self.my_method
    'MyClass.my_method'
  end
end

module MyModule
  refine MyClass.singleton_class do
    def my_method
      'Myclass.my_method in MyModule'
    end
  end
end

using MyModule

puts MyClass.my_method # Myclass.my_method in MyModule

方法2

selfを使わずクラスメソッドを定義

class MyClass
  def self.my_method
    'MyClass.my_method'
  end
end

module MyModule
  refine MyClass do
    def MyClass.my_method
      'Myclass.my_method in MyModule'
    end
  end
end

using MyModule

puts MyClass.my_method # Myclass.my_method in MyModule

もしくは

class MyClass
  def self.my_method
    'MyClass.my_method'
  end
end

module MyModule
  refine MyClass do
    class << MyClass
      def my_method
        'Myclass.my_method in MyModule'
      end
    end
  end
end

using MyModule

puts MyClass.my_method # Myclass.my_method in MyModule

selfの場合

うまく呼び出すことができない

class MyClass
  def self.my_method
    'MyClass.my_method'
  end
end

module MyModule
  refine MyClass do
    def self.my_method
      'Myclass.my_method in MyModule'
    end
  end
end

using MyModule

puts MyClass.my_method # 'MyClass.my_method'
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?