Skip to content

Instantly share code, notes, and snippets.

@rkh
Forked from lmarburger/hack.rb
Created May 17, 2012 16:31
Show Gist options
  • Select an option

  • Save rkh/2720016 to your computer and use it in GitHub Desktop.

Select an option

Save rkh/2720016 to your computer and use it in GitHub Desktop.

Revisions

  1. rkh revised this gist May 17, 2012. 1 changed file with 11 additions and 2 deletions.
    13 changes: 11 additions & 2 deletions hack.rb
    Original file line number Diff line number Diff line change
    @@ -14,11 +14,20 @@ def call
    end
    end

    module Prepending
    def append_features(base)
    return super unless base.is_a? Class
    prepend = self
    base.extend Module.new { define_method(:new) { |*| super.extend(prepend) }}
    end
    end

    p Base.new.call #=> "monkeypatched"

    # This is the spirit of what I'd like, but methods defined on the class will be
    # preferred over those in ancestors.
    module Override
    extend Prepending
    def call
    [ 'overridden', super ]
    end
    @@ -28,7 +37,7 @@ class Base
    include Override
    end

    p Base.new.call #=> "monkeypatched"
    p Base.new.call #=> ["overridden", "monkeypatched"]



    @@ -39,4 +48,4 @@ def call
    [ 'overridden', super ]
    end
    end
    p instance.call #=> ["overridden", "monkeypatched"]
    p instance.call #=> ["overridden", ["overridden", "monkeypatched"]]
  2. @lmarburger lmarburger created this gist May 17, 2012.
    42 changes: 42 additions & 0 deletions hack.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    class Base
    def call
    'call'
    end
    end

    p Base.new.call #=> "call"


    # Monkeypatching "works" but doesn't provide access to #super
    class Base
    def call
    'monkeypatched'
    end
    end

    p Base.new.call #=> "monkeypatched"

    # This is the spirit of what I'd like, but methods defined on the class will be
    # preferred over those in ancestors.
    module Override
    def call
    [ 'overridden', super ]
    end
    end

    class Base
    include Override
    end

    p Base.new.call #=> "monkeypatched"



    # This works but I don't have access to the class instances to apply this method.
    instance = Base.new
    class << instance
    def call
    [ 'overridden', super ]
    end
    end
    p instance.call #=> ["overridden", "monkeypatched"]