Guest User

Untitled

a guest
Apr 23rd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. Thread.abort_on_exception = true
  4.  
  5. class Starter
  6. attr_accessor :handler
  7.  
  8. def start
  9. @server = TCPServer.new(4254)
  10. loop do
  11. Thread.start(@server.accept) do |socket|
  12. puts "Got connection"
  13. while line = socket.gets.chomp
  14. @handler.dup.handle(socket, line) # I have to dup it, because it changes some
  15. # instance variables for use in the block
  16. end
  17. end
  18. end
  19. end
  20. end
  21.  
  22. class Handler
  23. def initialize(&block)
  24. @procedure = block
  25. end
  26.  
  27. def handle(socket, line)
  28. @line = line
  29. @socket = socket
  30. instance_eval(&@procedure) # This seems a bit hackish. I just want the method
  31. # `write` to be directly available in the block
  32. end
  33.  
  34. def write(line) # This is the method called from within the block
  35. @socket.write line.to_s + "\n"
  36. end
  37. end
  38.  
  39. s = Starter.new
  40. 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
  41. puts "Got: #{@line}"
  42. write "Hi, #@line. Wanna race?\n"
  43. sleep 5
  44. write "You're still here intact, #@line! :D\n"
  45. end
  46.  
  47. puts "Starting server ..."
  48. s.start
  49.  
  50. ## What I want
  51. s = Starter.new
  52. s.handler = Handler.new do |line| # or some other way to get the line (this will be broken up into keywords and arguments)
  53. if line == "foobar"
  54. write "You wrote foobar! I love you <3"
  55. else
  56. write "Don't you love me anymore ... ?"
  57. end
  58. end
Add Comment
Please, Sign In to add comment