LoginSignup
2
2

More than 5 years have passed since last update.

既存のメソッドを別物に置き換えてみる

Last updated at Posted at 2015-01-13

関連

やること

特定クラスのインスタンスメソッド、クラスメソッドを別物に置き換えてみる。
別のモジュールで置き換えのon/offを実装してみる。

使った要素技術と参考にしたサイト

やってみた

mock_methods.rb
class Hoge
  def hoge; p "hoge"; end
  def self.foo; p "foo"; end
end

module Mock
  extend self

  def on
    ::Hoge.class_eval do
      alias_method :__hoge, :hoge; remove_method :hoge
      class << ::Hoge; self; end.class_eval do
        alias_method :__foo, :foo; remove_method :foo
      end
      include ::Mock::Hoge
    end
  end

  def off
    ::Hoge.class_eval do
      alias_method :hoge, :__hoge; remove_method :__hoge
      class << ::Hoge; self; end.class_eval do
        alias_method :foo,  :__foo;  remove_method :__foo
      end
    end
  end

  module Hoge
    def hoge; p "hogeeeee"; end

    module ClassMethods
      def foo; p "fooooooo"; end
    end

    extend ClassMethods

    def self.included(klass)
      klass.extend ClassMethods
    end
  end
end

Hoge.new.hoge    #=> "hoge"
Hoge.foo         #=> "foo"

Mock.on
Hoge.new.hoge    #=> "hogeeeee"
Hoge.foo         #=> "fooooooo"

Mock.off
Hoge.new.hoge    #=> "hoge"
Hoge.foo         #=> "foo"
2
2
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
2
2