Guest User

Untitled

a guest
May 27th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. # = Exception-based Event Hooks
  2. #
  3. # Provides an Event Hooks system designed
  4. # on top of Ruby's built-in Exception system.
  5. #
  6. # def dothis2
  7. # puts 'pre'
  8. # hook :quitit
  9. # puts 'post'
  10. # end
  11. #
  12. # def tryit2
  13. # begin
  14. # puts "BEFORE"
  15. # dothis2
  16. # puts "AFTER"
  17. # rescue EventHook
  18. # event :quitit do
  19. # puts "HERE"
  20. # end
  21. # end
  22. # end
  23. #
  24. # tryit2
  25. #
  26. # produces
  27. #
  28. # BEFORE
  29. # pre
  30. # HERE
  31. # post
  32. # AFTER
  33. #
  34. # Note that EventHook use callcc.
  35.  
  36. class EventHook < Exception
  37. attr_reader :name, :cc
  38. def initialize(name, cc)
  39. @name = name
  40. @cc = cc
  41. end
  42. def call
  43. @cc.call
  44. end
  45. end
  46.  
  47. module Kernel
  48. def hook(sym)
  49. callcc{ |c| raise EventHook.new(sym, c) }
  50. end
  51. def event(sym)
  52. if $!.name == sym
  53. yield
  54. $!.call
  55. end
  56. end
  57. end
  58.  
  59.  
  60. # --- test ---
  61.  
  62. if $0 == __FILE__
  63.  
  64. require 'test/unit'
  65.  
  66. class TestEventHook < Test::Unit::TestCase
  67.  
  68. class T
  69. attr_reader :a
  70. def dothis
  71. @a << '{'
  72. hook :here
  73. @a << '}'
  74. end
  75. def tryit
  76. @a = ''
  77. begin
  78. @a << "["
  79. dothis
  80. @a << "]"
  81. rescue EventHook
  82. event :here do
  83. @a << "HERE"
  84. end
  85. end
  86. end
  87. end
  88.  
  89. def test_run
  90. t = T.new
  91. t.tryit
  92. assert_equal('[{HERE}]', t.a)
  93. end
  94.  
  95. end
  96.  
  97. end
Add Comment
Please, Sign In to add comment