Garbage Burrito

Save Some Code for Later with Ruby Procs

Save Some Code for Later with Ruby Procs
Ben Kittrell - 08 30, 2006 @ 11:40AM
Comments: 1

I was working on a BBCode parser for Rails, and Ryan B suggested that I use ruby for the codes, as opposed to just some regexp. So my first problem to solve was, how do I store a block of code to be used later on. "Well isn't that what methods are for?" you might say, well yeah, but this needs to be configurable. You don't want to have to create a method to add new codes. Luckily Ruby has Procs(or blocks, or closures, whatever!). A Proc is an object that represents a block of code. Since it's an object, it can be stored in a hash very easily. Here's the test script I created.

class Block
  def add_block(name, &block)
    blocks = Hash.new if @blocks.nil?
    @blocks[name] = block
  end

  def call_block(name, arg)
    @blocks[name].call(arg)
  end
end

The add_block method stores the provided block in a hash, and the call_block retrieves and executes it. I also allow one argument to be passed to the block. Here's an example of how to use this.

b = Block.new
b.add_block(:burrito) { |arg| 5.times { puts arg } }

b.call_block(:burrito, 'Hello Burrito!')

This will print 'Hello Burrito!' five times. Obviously this test script is pretty useless, but the concept opens up some cool possibilities.

I'm pretty excited about the BBCode parser though. Once we're done with the first release of rorBB, I'll post some more information about it.

Comments: 1

Comments

1. Doug - 04 24, 2008 @ 08:36AM

Very nice, one of the better explanations of procs :) thanks for helping my understanding further.

Post a Comment




powered by : Doodlekit Online Free Website Builder : developed by : Doodlebit™ Website Company