Skip to content

Instantly share code, notes, and snippets.

@rebo
Created January 11, 2013 17:02
Show Gist options
  • Select an option

  • Save rebo/4512320 to your computer and use it in GitHub Desktop.

Select an option

Save rebo/4512320 to your computer and use it in GitHub Desktop.
#
# Simple Context Example:
#
$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))
require 'hybrid_dci'
class Foo
include HybridDCI::Data
attr_reader :name ,:children
def initialize(name)
@name = name
@children = []
end
end
class SelfPreserve
include HybridDCI::Context
role :parent do
contract :children
def add_child(child)
self.children << child
end
end
role :new_child do
contract :name
def add_to_parent
ctx.parent(:call).add_child(self)
p "#{self.name}: I've been added!"
end
end
def initialize
@a_foo = Foo.new("Arthur")
@another_foo = Foo.new("Marvin")
p "Object ID of another_foo (which will play the role of child): #{@another_foo.object_id}"
bind_roles(:parent => @a_foo, :new_child=> @another_foo)
end
def execute
in_context do
new_child(:call).add_to_parent
p "Object ID of object in parents children array: #{parent.children.map(&:object_id)}"
p "Object ID of child object #{new_child.object_id}"
end
end
end
context = SelfPreserve.new
context.execute
# => nil
# >> "Object ID of another_foo (which will play the role of child): 70149730664240"
# >> "Marvin: I've been added!"
# >> "Object ID of object in parents children array: [70149730664240]"
# >> "Object ID of child object 70149730664240"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment