Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Forked from tatat/replace_method.rb
Last active July 8, 2019 20:31
Show Gist options
  • Select an option

  • Save Shinpeim/7227597 to your computer and use it in GitHub Desktop.

Select an option

Save Shinpeim/7227597 to your computer and use it in GitHub Desktop.

Revisions

  1. Shinpeim revised this gist Oct 30, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion replace_method.rb
    Original file line number Diff line number Diff line change
    @@ -31,4 +31,4 @@ def nyan_extended
    p nyan.nyan #=> :nyan_extented
    end

    p nyan.nyan
    p nyan.nyan #=> :nyan
  2. Shinpeim revised this gist Oct 30, 2013. 1 changed file with 15 additions and 11 deletions.
    26 changes: 15 additions & 11 deletions replace_method.rb
    Original file line number Diff line number Diff line change
    @@ -8,23 +8,27 @@ def replace_method(a, b)
    end
    end

    def method1
    :method1
    def with_replacing_method(a, b)
    replace_method(a, b)
    yield
    replace_method(b, a)
    end

    def method2
    :method2
    def nyan
    :nyan
    end

    def nyan_extended
    :nyan_extended
    end
    end

    nyan = Nyan.new

    p [nyan.method1, nyan.method2] #=> [:method1, :method2]

    nyan.replace_method :method1, :method2
    p nyan.nyan #=> :nyan

    p [nyan.method1, nyan.method2] #=> [:method2, :method1]

    nyan.replace_method :method1, :method2
    nyan.with_replacing_method(:nyan, :nyan_extended) do
    p nyan.nyan #=> :nyan_extented
    end

    p [nyan.method1, nyan.method2] #=> [:method1, :method2]
    p nyan.nyan
  3. @tatat tatat created this gist Oct 30, 2013.
    30 changes: 30 additions & 0 deletions replace_method.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    class Nyan
    def replace_method(a, b)
    (class << self; self end).module_exec do
    alias_method "#{a}_backup", a
    alias_method "#{b}_backup", b
    alias_method b, "#{a}_backup"
    alias_method a, "#{b}_backup"
    end
    end

    def method1
    :method1
    end

    def method2
    :method2
    end
    end

    nyan = Nyan.new

    p [nyan.method1, nyan.method2] #=> [:method1, :method2]

    nyan.replace_method :method1, :method2

    p [nyan.method1, nyan.method2] #=> [:method2, :method1]

    nyan.replace_method :method1, :method2

    p [nyan.method1, nyan.method2] #=> [:method1, :method2]