Skip to content

Commit

Permalink
Allow use cases to work with do notation
Browse files Browse the repository at this point in the history
  • Loading branch information
guilherme-andrade committed Jan 9, 2023
1 parent a5f9a4c commit a9677a0
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
use_cases (3.0.0)
use_cases (3.0.1)
activesupport (>= 6.1.7)
dry-matcher (>= 0.8.1)
dry-monads (>= 1.0.0)
Expand Down
1 change: 1 addition & 0 deletions lib/use_cases/module_optins/validated.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# frozen_string_literal: true

require "dry/validation"
require "dry/validation/contract"

module UseCases
Expand Down
14 changes: 12 additions & 2 deletions lib/use_cases/result.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,19 @@ def initialize(step, result)
@result = result
end

def method_missing(method, *args, &block)
return result.send(method, *args, &block) if result.respond_to?(method)

super
end

def respond_to_missing?(method, include_private = false)
result.respond_to?(method, include_private) || super
end

def value
return result if result_not_monad?
return nil if result_empty?
return if result_empty?

result.success? ? result.value! : result.failure
end
Expand All @@ -39,7 +49,7 @@ def nil?
end

def to_result
self
result
end

def result_empty?
Expand Down
2 changes: 1 addition & 1 deletion lib/use_cases/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module UseCases
VERSION = "3.0.1"
VERSION = "3.0.2"
end
27 changes: 27 additions & 0 deletions spec/support/test_subjects/operation_calling_use_case.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class OperationCallingUseCase
include Dry::Monads[:result]
include Dry::Monads::Do.for(:call)

def call
result = yield call_operation
Success(result)
end

private

def call_operation
operation = Operation.new
operation.call({})
end
end

# Path: spec/use_cases/steps/operation.rb
class Operation
include UseCase

step :step_1

def step_1
Success(:step_1)
end
end
16 changes: 16 additions & 0 deletions spec/use_cases/result_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
require 'spec_helper'

RSpec.describe UseCases::Result do
describe 'self' do
context 'when used by a service using the do notation' do
let(:caller) do
require 'support/test_subjects/operation_calling_use_case'
OperationCallingUseCase.new
end

it 'works' do
expect(caller.call).to be_success
end
end
end
end

0 comments on commit a9677a0

Please sign in to comment.