Skip to content

Commit

Permalink
Safer include and prepend with block.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Jul 19, 2024
1 parent ffdf1f3 commit 2a339d0
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 4 deletions.
42 changes: 40 additions & 2 deletions lib/sus/include_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,47 @@
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
def include_context(shared, *arguments, **options)
self.class_exec(*arguments, **options, &shared.block)
include IncludeContext::Helpers

def include_context(shared, ...)
shared.included(self, ...)
end
end
end
4 changes: 2 additions & 2 deletions lib/sus/it_behaves_like.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ def self.build(parent, shared, arguments = nil, unique: false, &block)
base.description = shared.name
base.identity = Identity.nested(parent.identity, base.description, unique: unique)
base.set_temporary_name("#{self}[#{base.description}]")

# User provided block is evaluated first, so that it can provide default behaviour for the shared context:
if block_given?
base.class_exec(*arguments, &block)
end

base.class_exec(*arguments, &shared.block)
return base
end
Expand Down
4 changes: 4 additions & 0 deletions lib/sus/shared.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ def self.build(name, block)

return base
end

def included(base, *arguments, **options)
base.class_exec(*arguments, **options, &self.block)
end
end

def self.Shared(name, &block)
Expand Down
16 changes: 16 additions & 0 deletions test/sus/include_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,31 @@

AThing = Sus::Shared("a thing") do |key, value: 42|
let(:a_thing) {{key => value}}

include do
def before
super

events << :shared_before
end
end
end

describe Sus::Context do
with '.include_context' do
with "a shared context with an option" do
let(:events) {Array.new}
include_context AThing, :key, value: 42

def before
super

events << :example_before
end

it "can include a shared context" do
expect(a_thing).to be == {:key => 42}
expect(events).to be == [:shared_before, :example_before]
end
end
end
Expand Down

0 comments on commit 2a339d0

Please sign in to comment.