Skip to content

Instantly share code, notes, and snippets.

@rebo
Created December 17, 2012 18:53
Show Gist options
  • Select an option

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

Select an option

Save rebo/4320853 to your computer and use it in GitHub Desktop.
#
# Fight.rb - showing overiding of instance methods and rebinding of a context.
#
#
#
#
require 'alias_dci'
class Battle
include AliasDCI::Context
role :lion do
def fight
p "#{name}: RAWR, I am a lion and I run fast."
end
end
role :bear do
def fight
p "#{name}: ARRR, I am a mighty bear and I will eat you."
end
end
def initialize(lion_player, bear_player)
rebind(lion_player, bear_player)
end
def rebind(lion_player, bear_player)
assign_named_roles(:lion => lion_player, :bear => bear_player)
end
def do_battle
in_context do
lion.fight
bear.fight
puts "\n\nLets have a party!"
TeaAndCakes.new(lion, bear).tea_party!
end
end
end
class TeaAndCakes
include AliasDCI::Context
role :tea_drinker do
contract :fight, :name
def fight_or_drink_tea
fight
puts "#{name}: I would rather drink tea"
end
end
role :cake_eater do
contract :fight, :name
def fight_or_eat_cake
fight
puts "#{name}: I would rather eat cake"
end
end
def initialize(tea_drinker, cake_eater)
rebind(tea_drinker, cake_eater)
end
def rebind(tea_drinker, cake_eater)
assign_named_roles(:tea_drinker => tea_drinker, :cake_eater => cake_eater)
end
def tea_party!
in_context do
tea_drinker.fight_or_drink_tea
cake_eater.fight_or_eat_cake
end
end
end
class Player < Struct.new(:name)
include AliasDCI::DataObject
def fight
puts "#{name}: I don't want to fight I'm a pacifist"
end
end
player_a = Player.new("Arthur Dent")
player_b = Player.new("Zaphod")
player_a.fight
player_b.fight
battle = Battle.new(player_a, player_b)
#round1
p "ROUND 1 : FIGHT"
battle.do_battle
# => nil
# >> Arthur Dent: I don't want to fight I'm a pacifist
# >> Zaphod: I don't want to fight I'm a pacifist
# >> "ROUND 1 : FIGHT"
# >> "Arthur Dent: RAWR, I am a lion and I run fast."
# >> "Zaphod: ARRR, I am a mighty bear and I will eat you."
# >>
# >>
# >> Lets have a party!
# >> Arthur Dent: I don't want to fight I'm a pacifist
# >> Arthur Dent: I would rather drink tea
# >> Zaphod: I don't want to fight I'm a pacifist
# >> Zaphod: I would rather eat cake
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment