Guest User

Untitled

a guest
May 20th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. class Op
  2. class FailedOp < StandardError;end
  3.  
  4. attr_accessor :params, :context
  5.  
  6. def initialize(params,context={})
  7. @params = params
  8. @context = context
  9. context[:success] ||= true
  10. end
  11.  
  12. def self.steps(&block)
  13. define_method :run, block
  14. end
  15.  
  16. def self.call(params, context={})
  17. op = self.new(params, context)
  18. op.run
  19. op
  20. end
  21.  
  22. def fail!(message)
  23. raise FailedOp.new(message)
  24. end
  25.  
  26. def failed?
  27. !success?
  28. end
  29.  
  30. def success?
  31. context[:success]
  32. end
  33.  
  34. def step(name_or_op=nil, &block)
  35. run_step(name_or_op, &block) unless failed?
  36. end
  37.  
  38. def failure(name_or_op=nil, &block)
  39. run_step(name_or_op, &block) unless success?
  40. end
  41.  
  42. def run_step(name_or_op, &block)
  43. if block_given?
  44. yield
  45. else
  46. case name_or_op
  47. when NilClass
  48. raise ArgumentError.new("step should have a name, proc or Op class if no block is given.")
  49. when String, Symbol
  50. method(name_or_op).call
  51. else
  52. name_or_op.call(params, context)
  53. end
  54. end
  55. rescue FailedOp => e
  56. context[:error] = e
  57. context[:success] = false
  58. context.freeze
  59. end
  60. end
  61.  
  62.  
  63.  
  64. class Op1 < Op
  65.  
  66. steps do
  67. step :one
  68. step :two
  69. step Op2
  70. step do
  71. step :four
  72. failure :five_fail
  73. end
  74. failure :ensure_bla
  75. end
  76.  
  77. def one
  78. puts "one #{params}"
  79. end
  80.  
  81. def two
  82. puts "two #{params}"
  83. end
  84.  
  85. def four
  86. puts "four #{params}"
  87. end
  88.  
  89. def five_fail
  90. puts "five_fail #{context}"
  91. end
  92.  
  93. def ensure_bla
  94. puts "ensure_bla #{context}"
  95. end
  96.  
  97. end
  98.  
  99. class Op2 < Op
  100.  
  101. steps do
  102. step :three
  103. end
  104.  
  105. def three
  106. fail!("Error")
  107. end
  108.  
  109. end
  110.  
  111. o = Op1.call({a: 1})
  112. # one {:a=>1}
  113. # two {:a=>1}
  114. # ensure_bla {:success=>false, :error=>#<Op::FailedOp: Error>}
  115. # => #<Op1:0x00007fda018180e8 @params={:a=>1}, @context={:success=>false, :error=>#<Op::FailedOp: Error>}>
  116. o.context
  117. #=> {:success=>false, :error=>#<Op::FailedOp: Error>}
  118. o.params
  119. #=> {:a=>1}
  120. o.failed?
  121. #=> true
  122. o.success?
  123. #=> false
Add Comment
Please, Sign In to add comment