|
| 1 | +module Graphiti |
| 2 | + module Util |
| 3 | + class TransactionHooksRecorder |
| 4 | + # This is a thread-global singleton class which is used to capture |
| 5 | + # the correct hooks to run when before and after transactions are |
| 6 | + # committed. Consuming code will call the #record method, which will |
| 7 | + # yield to the passed block: |
| 8 | + # |
| 9 | + # ```ruby |
| 10 | + # TransactionHooksRecorder.record do |
| 11 | + # TransactionHooksRecorder.add(->{ do_stuff() }, :before_commit) |
| 12 | + # TransactionHooksRecorder.add(->{ do_more_stuff() }, :after_commit) |
| 13 | + # { |
| 14 | + # result: do_the_main_thing_and_return_a_result() |
| 15 | + # } |
| 16 | + # end |
| 17 | + # ``` |
| 18 | + # |
| 19 | + # before_commit hooks will be executed before the record method returns. |
| 20 | + # All after_commit hooks will be added to the returned hash so that consumers |
| 21 | + # can decide when and whether to execute the callbacks. |
| 22 | + # |
| 23 | + # Returns a hash with `result` and `after_commit_hooks` keys. |
| 24 | + class << self |
| 25 | + def record |
| 26 | + reset_hooks |
| 27 | + |
| 28 | + begin |
| 29 | + result = yield |
| 30 | + run(:before_commit) |
| 31 | + |
| 32 | + unless result.kind_of?(::Hash) |
| 33 | + result = { result: result } |
| 34 | + end |
| 35 | + |
| 36 | + result.tap do |r| |
| 37 | + r[:after_commit_hooks] = hook_set(:after_commit) |
| 38 | + end |
| 39 | + ensure |
| 40 | + reset_hooks |
| 41 | + end |
| 42 | + end |
| 43 | + |
| 44 | + # Because hooks will be added from the outer edges of |
| 45 | + # the graph, working inwards |
| 46 | + def add(prc, lifecycle_event) |
| 47 | + hook_set(lifecycle_event).unshift(prc) |
| 48 | + end |
| 49 | + |
| 50 | + def run(lifecycle_event) |
| 51 | + _hooks[lifecycle_event].each { |h| h.call } |
| 52 | + end |
| 53 | + |
| 54 | + private |
| 55 | + def _hooks |
| 56 | + Thread.current[:_graphiti_hooks] |
| 57 | + end |
| 58 | + |
| 59 | + def reset_hooks |
| 60 | + Thread.current[:_graphiti_hooks] = { |
| 61 | + before_commit: [], |
| 62 | + after_commit: [], |
| 63 | + } |
| 64 | + end |
| 65 | + |
| 66 | + def hook_set(lifecycle_event) |
| 67 | + _hooks[lifecycle_event] |
| 68 | + end |
| 69 | + end |
| 70 | + end |
| 71 | + end |
| 72 | +end |
0 commit comments