Skip to content

Commit

Permalink
Tidy PlayerServer.
Browse files Browse the repository at this point in the history
  • Loading branch information
threedaymonk committed Oct 2, 2011
1 parent f0e5c12 commit 7185777
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 26 deletions.
2 changes: 1 addition & 1 deletion bin/play.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def method_missing(m, *args)
end

def kill
@object.die(@secret)
@object.stop(@secret)
end
end

Expand Down
47 changes: 22 additions & 25 deletions bin/player_server.rb
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
$:.unshift File.expand_path("../../lib", __FILE__)
require "drb"
require "forwardable"
require "battleship/util"

module Battleship
class PlayerServer
include Battleship::Util
extend Forwardable
METHODS = [:name, :new_game, :take_turn]

def initialize
class_name = Module.constants.find{ |c| is_player?(c) }
@player_class = Module.const_get(class_name)
@player_class = find_player_classes.first
@player = @player_class.new
end

Expand All @@ -18,36 +19,32 @@ def new_game
@player = @player_class.new
@player.new_game
end

# Ick. Dirty. Is there a cleaner way?
def die
DRb.stop_service
end

private
def is_player?(class_name)
class_name.to_s =~ /Player$/ &&
(Module.const_get(class_name).instance_methods && METHODS) == METHODS
end
end

class ValidatingProxy
class ValidatingServer
include DRbUndumped

ValidationError = Class.new(RuntimeError)

def initialize(secret, object)
def initialize(secret, object, port)
@secret = secret
@object = object
DRb.start_service "druby://localhost:#{port}", self
end

def method_missing(m, *args)
secret = args.shift
if secret == @secret
@object.__send__(m, *args)
else
raise ValidationError
end
validate!(args.shift)
@object.__send__(m, *args)
end

def stop(secret)
validate!(secret)
DRb.stop_service
end

private
def validate!(secret)
raise ValidationError unless secret == @secret
end
end
end
Expand All @@ -56,9 +53,9 @@ def method_missing(m, *args)
$:.unshift File.join(File.dirname(path), "lib")
load path

client = Battleship::ValidatingProxy.new(secret, Battleship::PlayerServer.new)

DRb.start_service "druby://localhost:#{port}", client
Battleship::ValidatingServer.new(
secret, Battleship::PlayerServer.new, port
)
}.call(*ARGV)

DRb.thread.join
14 changes: 14 additions & 0 deletions lib/battleship/util.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module Battleship
module Util
PLAYER_METHODS = [:name, :new_game, :take_turn]

def find_player_classes
Module.constants.
select { |sym| sym.to_s =~ /Player$/ }.
map { |sym| Module.const_get(sym) }.
select { |klass|
(klass.instance_methods & PLAYER_METHODS) == PLAYER_METHODS
}
end
end
end

0 comments on commit 7185777

Please sign in to comment.