2021-01-09 18:06:59 +00:00
|
|
|
require "./label"
|
2021-02-13 05:46:22 +00:00
|
|
|
require "./location"
|
2021-01-09 18:06:59 +00:00
|
|
|
|
|
|
|
module Spectator
|
2021-01-09 19:04:27 +00:00
|
|
|
# Information about a hook tied to an example group and a proc to invoke it.
|
2021-01-09 18:06:59 +00:00
|
|
|
class ExampleGroupHook
|
|
|
|
# Location of the hook in source code.
|
2021-02-13 05:46:22 +00:00
|
|
|
getter! location : Location
|
2021-01-09 18:06:59 +00:00
|
|
|
|
|
|
|
# User-defined description of the hook.
|
|
|
|
getter! label : Label
|
|
|
|
|
2021-01-09 19:04:27 +00:00
|
|
|
@proc : ->
|
2021-08-08 03:45:49 +00:00
|
|
|
@called = Atomic::Flag.new
|
2021-01-09 19:04:27 +00:00
|
|
|
|
|
|
|
# Creates the hook with a proc.
|
|
|
|
# The *proc* will be called when the hook is invoked.
|
2021-02-13 05:46:22 +00:00
|
|
|
# A *location* and *label* can be provided for debugging.
|
|
|
|
def initialize(@proc : (->), *, @location : Location? = nil, @label : Label = nil)
|
2021-01-09 18:06:59 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# Creates the hook with a block.
|
|
|
|
# The block will be executed when the hook is invoked.
|
2021-02-13 05:46:22 +00:00
|
|
|
# A *location* and *label* can be provided for debugging.
|
|
|
|
def initialize(*, @location : Location? = nil, @label : Label = nil, &block : -> _)
|
2021-01-09 19:04:27 +00:00
|
|
|
@proc = block
|
2021-01-09 18:06:59 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# Invokes the hook.
|
|
|
|
def call : Nil
|
2021-08-08 03:45:49 +00:00
|
|
|
@called.test_and_set
|
2021-01-09 19:04:27 +00:00
|
|
|
@proc.call
|
2021-01-09 18:06:59 +00:00
|
|
|
end
|
2021-01-09 18:14:27 +00:00
|
|
|
|
2021-08-08 03:45:49 +00:00
|
|
|
# Invokes the hook if it hasn't already been invoked.
|
|
|
|
# Returns true if the hook was invoked (first time being called).
|
|
|
|
def call_once : Bool
|
|
|
|
first = @called.test_and_set
|
|
|
|
@proc.call if first
|
|
|
|
first
|
|
|
|
end
|
|
|
|
|
2021-01-09 18:14:27 +00:00
|
|
|
# Produces the string representation of the hook.
|
2021-02-13 05:46:22 +00:00
|
|
|
# Includes the location and label if they're not nil.
|
2022-11-05 02:56:02 +00:00
|
|
|
def to_s(io : IO) : Nil
|
2021-01-09 18:14:27 +00:00
|
|
|
io << "example group hook"
|
|
|
|
|
|
|
|
if (label = @label)
|
2021-05-30 20:21:42 +00:00
|
|
|
io << ' ' << label
|
2021-01-09 18:14:27 +00:00
|
|
|
end
|
|
|
|
|
2021-02-13 05:46:22 +00:00
|
|
|
if (location = @location)
|
2021-05-30 20:21:42 +00:00
|
|
|
io << " @ " << location
|
2021-01-09 18:14:27 +00:00
|
|
|
end
|
|
|
|
end
|
2021-01-09 18:06:59 +00:00
|
|
|
end
|
|
|
|
end
|