Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- Thread.abort_on_exception = true
- class Starter
- attr_accessor :handler
- def start
- @server = TCPServer.new(4254)
- loop do
- Thread.start(@server.accept) do |socket|
- puts "Got connection"
- while line = socket.gets.chomp
- @handler.dup.handle(socket, line) # I have to dup it, because it changes some
- # instance variables for use in the block
- end
- end
- end
- end
- end
- class Handler
- def initialize(&block)
- @procedure = block
- end
- def handle(socket, line)
- @line = line
- @socket = socket
- instance_eval(&@procedure) # This seems a bit hackish. I just want the method
- # `write` to be directly available in the block
- end
- def write(line) # This is the method called from within the block
- @socket.write line.to_s + "\n"
- end
- end
- s = Starter.new
- s.handler = Handler.new do # The syntax here is the only thing set I'm actively aiming for. I don't want to write stuff like Handler.new do |socket,line| socket.write line + "\n" end. I'd prefer passing the line as an argument, though
- puts "Got: #{@line}"
- write "Hi, #@line. Wanna race?\n"
- sleep 5
- write "You're still here intact, #@line! :D\n"
- end
- puts "Starting server ..."
- s.start
- ## What I want
- s = Starter.new
- s.handler = Handler.new do |line| # or some other way to get the line (this will be broken up into keywords and arguments)
- if line == "foobar"
- write "You wrote foobar! I love you <3"
- else
- write "Don't you love me anymore ... ?"
- end
- end
Add Comment
Please, Sign In to add comment