diff --git a/lib/interactor/context.rb b/lib/interactor/context.rb index d9ce24d..1402e60 100644 --- a/lib/interactor/context.rb +++ b/lib/interactor/context.rb @@ -181,5 +181,32 @@ def rollback! def _called @called ||= [] end + + # Internal: Support for ruby 3.0 pattern matching + # + # Examples + # + # context = MyInteractor.call(foo: "bar") + # + # # => # + # context => { foo: } + # foo == "bar" + # # => true + # + # + # case context + # in success: true, result: { first:, second: } + # do_stuff(first, second) + # in failure: true, error_message: + # log_error(message: error_message) + # end + # + # Returns the context as a hash, including success and failure + def deconstruct_keys(keys) + to_h.merge( + success: success?, + failure: failure? + ) + end end end diff --git a/spec/interactor/context_spec.rb b/spec/interactor/context_spec.rb index 1769172..1696b4f 100644 --- a/spec/interactor/context_spec.rb +++ b/spec/interactor/context_spec.rb @@ -199,5 +199,20 @@ module Interactor expect(context._called).to eq([]) end end + + describe '#deconstruct_keys' do + let(:context) { Context.build(foo: :bar) } + + let(:deconstructed) { context.deconstruct_keys([:foo, :success, :failure]) } + + it 'deconstructs as hash pattern' do + expect(deconstructed[:foo]).to eq(:bar) + end + + it 'includes success and failure' do + expect(deconstructed[:success]).to eq(true) + expect(deconstructed[:failure]).to eq(false) + end + end end end