Skip to content

Commit

Permalink
Adds support for ruby 3.0 pattern matching (#200)
Browse files Browse the repository at this point in the history
Adds support for ruby 3.0 pattern matching
  • Loading branch information
bonflintstone authored Dec 28, 2024
1 parent 588a7c9 commit 2764aa3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/interactor/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,5 +181,32 @@ def rollback!
def _called
@called ||= []
end

# Internal: Support for ruby 3.0 pattern matching
#
# Examples
#
# context = MyInteractor.call(foo: "bar")
#
# # => #<Interactor::Context 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
15 changes: 15 additions & 0 deletions spec/interactor/context_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 2764aa3

Please sign in to comment.