require 'objectteam'

# The class ===================================
class Simple
  
  # attribute name
  attr :name

  # ctor
  def initialize(name)
    @name = name
  end

  # say hello
  def hello()
    print "hello from #{@name}\n"
  end

  def to_s
    @name
  end
end


# The "collaboration" :) =====================
# 
# This Team defines a counting role class with
# an inc method, that increments the counter.
class Count < Team
  class Counter

    # the counter
    attr :count
    
    # ctor
    def initialize()
      @count=0
    end

    # increment count
    def inc()
      @count += 1
      print "#{@count}.th time: "
    end
  end
end

# The connector ==============================
#
# With this connector we define a counting hello method.
# Each time hello is invoked, inc is called before to
# count the number of hello's.
# Counting is done only in context of instances of this
# connector.
class CountHello < Count
  # Counter played by Simple
  play_role(Counter, Simple) {
    # invoke inc on Role
    before("inc", "hello")
  }
end
    
if __FILE__ == $0

  # The test ===================================

  #create 2 instances of Simple.
  e = Simple.new("earth")
  m = Simple.new("mars")
  #create connector.
  countteam = CountHello.new()

  #invoke normal hello (no count)
  e.hello
  m.hello

  #activate connector
  countteam.while_active {
    #each call is counted
    e.hello
    e.hello
    m.hello
    m.hello
  }

  #connector is not longer active
  #invoke normal hello (no count)
  e.hello
  m.hello
end


syntax highlighted by Code2HTML, v. 0.9.1