Skip to content

Instantly share code, notes, and snippets.

@panw
Last active January 12, 2017 14:08
Show Gist options
  • Save panw/96695296e816de1b10d5e4cd50e45796 to your computer and use it in GitHub Desktop.
Save panw/96695296e816de1b10d5e4cd50e45796 to your computer and use it in GitHub Desktop.
class Gumball
attr_reader :color, :flavor
DEFAULT_COLORS = ['red', 'green', 'blue']
DEFAULT_FLAVORS = ['sour apple', 'bacon', 'gravy']
def initialize(options={})
@color = options.fetch(:color) { DEFAULT_COLORS.sample }
@flavor = options.fetch(:flavor) { DEFAULT_FLAVORS.sample }
end
end
class GumballMachine
attr_reader :gumballs
def initialize(options={})
@gumballs = []
end
def insert_coin
@gumballs.shuffle.pop
end
def refill
if @gumballs.empty?
100.times do
@gumballs << Gumball.new
end
end
end
end
class GumballMachineController
def initialize(view, machine)
@view = view
@machine = machine
end
def run
input = @view.welcome_prompt
until input.downcase == "n"
@view.list_gumballs(@machine.gumballs)
coin = @view.ask_for_coin
@view.give_gumball(@machine.insert_coin)
input = @view.reprompt
end
@view.exit_message
end
end
class GumballMachineTerminalView
def welcome_prompt
puts "Hello, I am a gumball machine."
puts "Are you interested in a gumball? (y/n)"
input = gets.chomp
end
def list_gumballs(gumballs)
# List all gumballs in the machine
puts "Here are all the gumballs"
puts "#{gumballs.map{ |gumball| gumball.color.capitalize }.join(' gumball, ')}"
puts "You won't know the flavor until you try it. Enjoy :)"
puts
end
def ask_for_coin
puts "Please insert a coin"
gets.chomp
end
def give_gumball(gumball)
puts "You got a #{gumball.color} gumball that is flavored with #{gumball.flavor}"
puts
end
def reprompt
puts "Would you like another gumball? (y/n)"
gets.chomp
end
def exit_message
puts "That's your loss"
puts
end
end
gumball_machine = GumballMachine.new
gumball_machine_view = GumballMachineTerminalView.new
gumball_machine.refill
gumball_machine_controller = GumballMachineController.new(gumball_machine_view, gumball_machine)
gumball_machine_controller.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment