method mixin?

Discussion in 'Ruby' started by Cnm Cnm, Aug 20, 2010.

  1. Cnm Cnm

    Cnm Cnm Guest

    Just wonder is there any way to inject a bunch of code into an instance
    method, just like how a module can be used as a mixin to a class?
    --
    Posted via http://www.ruby-forum.com/.
    Cnm Cnm, Aug 20, 2010
    #1
    1. Advertising

  2. On 20.08.2010 03:03, Cnm Cnm wrote:
    > Just wonder is there any way to inject a bunch of code into an instance
    > method, just like how a module can be used as a mixin to a class?


    One thing you can do is alias the original and use it.

    class Foo
    def bar; puts 123; end
    end

    f = Foo.new
    f.bar

    class Foo
    alias _bar bar

    def bar
    puts "before"
    x = _bar
    puts "after"
    x
    end
    end

    f.bar

    I once did some meta programming to nicely declare before and after code
    but that code was never production ready. IIRC others did similar things.

    Kind regards

    robert

    --
    remember.guy do |as, often| as.you_can - without end
    http://blog.rubybestpractices.com/
    Robert Klemme, Aug 20, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mac
    Replies:
    1
    Views:
    582
  2. Ben
    Replies:
    3
    Views:
    232
  3. Replies:
    13
    Views:
    340
    Robert Klemme
    Nov 7, 2005
  4. Farrel Lifson

    Mixin a module method as a class method

    Farrel Lifson, Oct 18, 2006, in forum: Ruby
    Replies:
    9
    Views:
    124
    Trans
    Oct 19, 2006
  5. Andrew Stewart

    Overridding A Method Via A Mixin

    Andrew Stewart, Jan 15, 2008, in forum: Ruby
    Replies:
    15
    Views:
    226
    Andrew Stewart
    Jan 17, 2008
Loading...

Share This Page