Skip to content

Commit 2764aa3

Browse files
Adds support for ruby 3.0 pattern matching (#200)
Adds support for ruby 3.0 pattern matching
1 parent 588a7c9 commit 2764aa3

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

lib/interactor/context.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,5 +181,32 @@ def rollback!
181181
def _called
182182
@called ||= []
183183
end
184+
185+
# Internal: Support for ruby 3.0 pattern matching
186+
#
187+
# Examples
188+
#
189+
# context = MyInteractor.call(foo: "bar")
190+
#
191+
# # => #<Interactor::Context foo="bar">
192+
# context => { foo: }
193+
# foo == "bar"
194+
# # => true
195+
#
196+
#
197+
# case context
198+
# in success: true, result: { first:, second: }
199+
# do_stuff(first, second)
200+
# in failure: true, error_message:
201+
# log_error(message: error_message)
202+
# end
203+
#
204+
# Returns the context as a hash, including success and failure
205+
def deconstruct_keys(keys)
206+
to_h.merge(
207+
success: success?,
208+
failure: failure?
209+
)
210+
end
184211
end
185212
end

spec/interactor/context_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,5 +199,20 @@ module Interactor
199199
expect(context._called).to eq([])
200200
end
201201
end
202+
203+
describe '#deconstruct_keys' do
204+
let(:context) { Context.build(foo: :bar) }
205+
206+
let(:deconstructed) { context.deconstruct_keys([:foo, :success, :failure]) }
207+
208+
it 'deconstructs as hash pattern' do
209+
expect(deconstructed[:foo]).to eq(:bar)
210+
end
211+
212+
it 'includes success and failure' do
213+
expect(deconstructed[:success]).to eq(true)
214+
expect(deconstructed[:failure]).to eq(false)
215+
end
216+
end
202217
end
203218
end

0 commit comments

Comments
 (0)