Class: Origen::Utility::BlockArgs

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/origen/utility/block_args.rb

Overview

BlockArgs provides a neat way to pass multiple block arguments to a method that the method can then used in various ways.

(blocks in Ruby are merely nameless methods you can pass to methods as an argument. Used to pass ruby code to a method basically.)

A single BlockArgs object is an array of these blocks that can be added or deleted.

def handle_some_blocks(options={})

  blockA = Origen::Utility::BlockArgs.new
  blockB = Origen::Utility::BlockArgs.new

  yield blockA, blockB

  puts "Handling blocks!"

  if options[:block_to_run] == :blockA
    blockA.each do |block|
      block.call
    end
  else
    blockB.each do |block|
      block.call
    end
  end

  puts "Done handling blocks!"

end

To then use the above method:

handle_some_blocks(options) do |blockA, blockB|
  blockA.add do
    puts "do task 1"
  end
  blockA.add do
    puts "do task 2"
  end
  blockB.add do
    puts "do task 3"
  end
end

Many blocks can be added in this case to either the blockA or blockB BlockArg objects. The only reason 2 BlockArg objects are used above is that handle_some_blocks wants to use different blocks depending on an option argument.

This is a very powerful way to put code specific to one application in a different method in different class (e.g. handle_some_blocks) where the code calling it doesn't need to know exact implementation details.

Constant Summary

Constants included from Enumerable

Enumerable::PRIMATIVES

Instance Method Summary collapse

Methods included from Enumerable

#debug, #list

Constructor Details

#initializeBlockArgs

Creates a new BlockArgs object



62
63
64
# File 'lib/origen/utility/block_args.rb', line 62

def initialize
  @block_args = []
end

Instance Method Details

#add(&block) ⇒ Object

Adds a block to the BlockArgs object



67
68
69
# File 'lib/origen/utility/block_args.rb', line 67

def add(&block)
  @block_args << block
end

#delete(&block) ⇒ Object

Deletes a block to the BlockArgs object



72
73
74
# File 'lib/origen/utility/block_args.rb', line 72

def delete(&block)
  @block_args.delete(block)
end

#eachObject

required to enumerate objects for Enumerable iterator returns each block at a time



78
79
80
81
82
# File 'lib/origen/utility/block_args.rb', line 78

def each
  @block_args.each do |arg|
    yield arg
  end
end

#each_indexObject

same as each but returns index of each block instead of block itself.



86
87
88
89
90
# File 'lib/origen/utility/block_args.rb', line 86

def each_index
  @block_args.each_index do |i|
    yield i
  end
end