Skip to content

Instantly share code, notes, and snippets.

@krzykamil
Created April 20, 2023 10:39
Show Gist options
  • Save krzykamil/6ada1c1487266e1126b39323f438fca7 to your computer and use it in GitHub Desktop.
Save krzykamil/6ada1c1487266e1126b39323f438fca7 to your computer and use it in GitHub Desktop.
State (write) dry-effect
✓ ruby stack.rb
What do you want to do? (add, remove, see, count)
see
#<Plate:0x0000557c3f0598b0>
What do you want to do? (add, remove, see, count)
add
#<Plate:0x0000557c3f059c20>
#<Plate:0x0000557c3f0598b0>
#<Plate:0x0000557c3f890ce0>
What do you want to do? (add, remove, see, count)
count
3
What do you want to do? (add, remove, see, count)
see
#<Plate:0x0000557c3f890ce0>
What do you want to do? (add, remove, see, count)
remove
#<Plate:0x0000557c3f059c20>
#<Plate:0x0000557c3f0598b0>
What do you want to do? (add, remove, see, count)
count
2
What do you want to do? (add, remove, see, count)
remove
#<Plate:0x0000557c3f059c20>
Bye!
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'dry-effects'
end
require 'dry/effects'
class Plate; end
class Stack
def initialize(size)
@stack = size.times.map{ |_| Plate.new }
end
private attr_reader :stack
def push(value)
stack.push(value)
end
def pop
stack.tap(&:pop)
end
def peek
stack.last
end
def stock
stack.size
end
end
class App
include Dry::Effects::Handler.State(:stack)
def initialize
@stack = Stack.new(2)
end
def call
with_stack(@stack) do
Machine.new.call
end
puts "Bye!"
end
end
class Machine
include Dry::Effects.State(:stack)
def call
while stack.stock > 1
puts "What do you want to do? (add, remove, see, count)"
input = gets.chomp
case input
when "add" then puts stack.push(Plate.new)
when "remove" then puts stack.pop
when "see" then puts stack.peek
when "count" then puts stack.stock
else puts "Wrong input, allowed commands: add, remove, see, count"
end
end
end
end
app = App.new.()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment