Ruby hackery needed

Here’s a kind of code I find myself habitually writing until I realize I can’t implement it:


    watch {
      # some calculation
    }.and_whenever(:something_happened) {
      # do something
    }.and_whenever(:something_else_happened) {
      # do something else
    }

What I want this to do is:

  • Stash away the block with “some calculation”

  • Run the second block. This does something that will affect the calculation.

  • Run the third block. This does something else that will affect the calculation.

  • Run the first block, then undo the effects of the following blocks.

The problem is that I don’t see a way to know when you’ve reached the end of the chain of 2nd, 3rd, … blocks, and it’s now time to execute the first block.

Now, there are alternatives. You can put the blocks in the right order. You can make a single and_whenever that takes a hash from names to lambdas as its single argument (presuming the order of evaluation doesn’t matter). You can put a “sentinel” method at the end of the chain, like .ok_do_it_now.

What I’m wondering if there’s some clever way of making the original form work.

One Response to “Ruby hackery needed”

  1. WesMaldonado Says:

    Have a look at http://god.rubyforge.org They have a syntax that is close to this:
    God.watch do |w|
    w.oncondition(:some_condition) do
    end
    end

    And you could probably do this with AOP: http://aquarium.rubyforge.org/examples.html

Leave a Reply

You must be logged in to post a comment.