Skip to content

Commit

Permalink
Add before/after/around helpers.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Jul 22, 2024
1 parent 2a339d0 commit be47581
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 47 deletions.
36 changes: 36 additions & 0 deletions lib/sus/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,41 @@ def each(&block)
end
end
end

def before(&block)
wrapper = Module.new

wrapper.define_method(:before) do
super()
instance_exec(&block)
end

self.include(wrapper)
end

def after(&block)
wrapper = Module.new

wrapper.define_method(:after) do
instance_exec(&block)
super()
end

self.include(wrapper)
end

def around(&block)
wrapper = Module.new

wrapper.define_method(:around) do
call_super = proc do
super()
end

instance_exec(call_super, &block)
end

self.include(wrapper)
end
end
end
38 changes: 0 additions & 38 deletions lib/sus/include_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,45 +6,7 @@
require_relative 'context'

module Sus
module IncludeContext
module Helpers
def prepend(*arguments, &block)
arguments.each do |argument|
if argument.class == Module
super(argument)
else
argument.prepended(self)
end
end

if block_given?
wrapper = Module.new
wrapper.instance_exec(&block)
super(wrapper)
end
end

def include(*arguments, &block)
arguments.each do |argument|
if argument.class == Module
super(argument)
else
argument.included(self)
end
end

if block_given?
wrapper = Module.new
wrapper.module_exec(&block)
super(wrapper)
end
end
end
end

module Context
include IncludeContext::Helpers

def include_context(shared, ...)
shared.included(self, ...)
end
Expand Down
23 changes: 14 additions & 9 deletions test/sus/include_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@
AThing = Sus::Shared("a thing") do |key, value: 42|
let(:a_thing) {{key => value}}

include do
def before
super

events << :shared_before
end
before do
$stderr.puts "before: #{self}"
events << :shared_before
end

after do
$stderr.puts "after: #{self}"
events << :shared_after
end

around do |block|
$stderr.puts "around: #{self}"
block.call
end
end

Expand All @@ -21,9 +28,7 @@ def before
let(:events) {Array.new}
include_context AThing, :key, value: 42

def before
super

before do
events << :example_before
end

Expand Down

0 comments on commit be47581

Please sign in to comment.