Adding code/Extending methods after they have been written?

Discussion in 'Ruby' started by Marc Heiler, Jan 26, 2008.

  1. Marc Heiler

    Marc Heiler Guest

    Hi there,

    Let's say i have 10 methods. Each one looks like so:

    def p(some_input)
    print some_input
    # do some more stuff...
    end

    Some months after I wrote this, I realized that I need to
    handle blocks given to these methods. (Need is the wrong
    word, a better word would be i *want to* because
    Ruby allows you to)

    I do it like so currently:

    if block_given?
    yield
    some_mandatory_finalizer_method
    end

    The thing actually is... The last 4 lines of code look
    like repetitive boilerplate code to me. The way I solved it
    was by copy pasting this segment into each method, but
    it kinda does not feel clean. (I have even put these
    four lines of code into one line, so that I have
    an easier time to remove this code if i can think of a
    cleaner solution)

    Does anyone else of you know of a way to add "code rules"
    to some methods? Something like this would be cool:

    def add_boilerplate_code
    if block_given?
    yield
    some_mandatory_finalizer_method # this is always the same method
    end
    end

    METHODS_THAT_NEED_TO_BE_EXTENDED = %w( p q r s t u v w x y z )
    METHODS_THAT_NEED_TO_BE_EXTENDED.each do |my_method|
    my_method.add_boilerplate_code
    end


    Thankful for any tips!
    --
    Posted via http://www.ruby-forum.com/.
    Marc Heiler, Jan 26, 2008
    #1
    1. Advertising

  2. Marc Heiler

    Stefan Lang Guest

    > Does anyone else of you know of a way to add "code rules"
    > to some methods? Something like this would be cool:


    Looks like a good use case for Aspect oriented programming.
    AOP frameworks provide mechanisms to do exactly that.
    There are (at least) two AOP frameworks on RubyForge:
    aspectr and aquarium.

    Otherwise it's fairly easy to create such a facility
    from scratch via alias_method.
    Stefan Lang, Jan 26, 2008
    #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. Nicola Larosa

    Scribus could have been written in Python

    Nicola Larosa, Sep 17, 2004, in forum: Python
    Replies:
    0
    Views:
    317
    Nicola Larosa
    Sep 17, 2004
  2. Replies:
    0
    Views:
    623
  3. David A. Black
    Replies:
    2
    Views:
    213
    Tim Hunter
    Aug 19, 2004
  4. Replies:
    13
    Views:
    199
    Calamitas
    Mar 18, 2009
  5. Simon Wigzell

    How do links know they have been visited?

    Simon Wigzell, Jun 27, 2008, in forum: Javascript
    Replies:
    3
    Views:
    143
    Simon Wigzell
    Jun 28, 2008
Loading...

Share This Page