Skip to content

Instantly share code, notes, and snippets.

@zackchandler
Created May 27, 2010 04:16
Show Gist options
  • Save zackchandler/415452 to your computer and use it in GitHub Desktop.
Save zackchandler/415452 to your computer and use it in GitHub Desktop.
SIZES = Hash.new(0) # return zero for any unknown size
SIZES[:small] = 1
SIZES[:medium] = 2
SIZES[:large] = 3
class Plane
attr_accessor :type, :size
attr_reader :priority
def initialize(options={})
@type = options[:type]
@size = options[:size]
@priority = SIZES[@size]
end
end
class PrivatePlane < Plane
def initialize(options={})
super(options.update(:type => 'Private'))
@priority = 10 + SIZES[@size]
end
end
class CommercialPlane < Plane
def initialize(options={})
super(options.update(:type => 'Commercial'))
@priority = 100 + SIZES[@size]
end
end
class AirForceOne < Plane
def initialize(options={})
super(options.update(:type => 'Air Force One'))
@priority = 1_000_000
end
end
class PlaneQueue
attr_reader :queue
def initialize
@queue = []
end
def <<(plane)
@queue.unshift(plane)
end
def next_plane_to_land
@queue.sort{ |p1,p2| p2.priority <=> p1.priority }.shift
end
def inspect
@queue.inspect
end
end
if __FILE__ == $0 # run tests
require 'test/unit'
class PlaneTests < Test::Unit::TestCase
def test_default_types
assert_equal 'Private', PrivatePlane.new.type
assert_equal 'Commercial', CommercialPlane.new.type
end
def test_default_priorities
assert_equal 10, PrivatePlane.new.priority
assert_equal 100, CommercialPlane.new.priority
end
def test_larger_size_has_higher_priority
small_plane = PrivatePlane.new(:size => :small)
medium_plane = PrivatePlane.new(:size => :medium)
assert medium_plane.priority > small_plane.priority
end
def test_commercial_has_higher_priority_than_private_regardless_of_size
private_plane = PrivatePlane.new(:size => :large)
commericial_plane = CommercialPlane.new(:size => :small)
assert commericial_plane.priority > private_plane.priority
end
def test_air_force_one_has_highest_priority
other_plane = CommercialPlane.new(:size => :large)
air_force_one = AirForceOne.new
assert air_force_one.priority > other_plane.priority
end
end
class PlaneQueueTests < Test::Unit::TestCase
def setup
@queue = PlaneQueue.new
end
def test_empty_queue
assert_equal nil, @queue.next_plane_to_land
end
def test_large_size_has_higher_priority
@queue << CommercialPlane.new(:size => :small)
@queue << CommercialPlane.new(:size => :large)
@queue << CommercialPlane.new(:size => :medium)
assert_equal :large, @queue.next_plane_to_land.size
end
def test_commericial_has_higher_priority
@queue << PrivatePlane.new
@queue << CommercialPlane.new
@queue << PrivatePlane.new
assert_equal CommercialPlane, @queue.next_plane_to_land.class
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment