Skip to content

Commit

Permalink
Don't mutate interactor state in case of error. Log errors with result.
Browse files Browse the repository at this point in the history
  • Loading branch information
jodosha committed Jun 9, 2015
1 parent 131bd9a commit f2566fd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
15 changes: 10 additions & 5 deletions lib/lotus/interactor.rb
Expand Up @@ -29,6 +29,7 @@ class Result < Utils::BasicObject
# @api private
def initialize(payload = {})
@payload = _payload(payload)
@errors = []
@success = true
end

Expand Down Expand Up @@ -59,7 +60,14 @@ def fail!
# @see Lotus::Interactor#error
# @see Lotus::Interactor#error!
def errors
@payload.fetch(:_errors) { [] }
@errors.dup
end

# @since x.x.x
# @api private
def add_error(*errors)
@errors << errors
@errors.flatten!
end

# Returns the first errors collected during an operation
Expand Down Expand Up @@ -161,7 +169,6 @@ def initialize(*args)
super
ensure
@__result = ::Lotus::Interactor::Result.new
@_errors = []
end

# Triggers the operation and return a result.
Expand Down Expand Up @@ -343,7 +350,7 @@ def fail!
# result.errors # => ["Prepare data error", "Persist error"]
# result.logger # => [:prepare_data!, :persist!, :sync!]
def error(message)
@_errors << message
@__result.add_error << message
false
end

Expand Down Expand Up @@ -444,8 +451,6 @@ def self.extended(interactor)

class_attribute :exposures
self.exposures = Utils::Hash.new

expose :_errors
end
end

Expand Down
15 changes: 12 additions & 3 deletions test/interactor_test.rb
Expand Up @@ -285,7 +285,7 @@ def initialize(user, params)
describe "when it has errors" do
it "isn't successful" do
result = Lotus::Interactor::Result.new
result.prepare!(_errors: ["There was a problem"])
result.add_error "There was a problem"
assert !result.success?, "Expected `result' to NOT be successful"
end
end
Expand Down Expand Up @@ -324,7 +324,16 @@ def initialize(user, params)

it "returns all the errors" do
result = Lotus::Interactor::Result.new
result.prepare!(_errors: ['Error 1', 'Error 2'])
result.add_error ['Error 1', 'Error 2']

result.errors.must_equal ['Error 1', 'Error 2']
end

it "prevents information escape" do
result = Lotus::Interactor::Result.new
result.add_error ['Error 1', 'Error 2']

result.errors.clear

result.errors.must_equal ['Error 1', 'Error 2']
end
Expand All @@ -338,7 +347,7 @@ def initialize(user, params)

it "returns only the first error" do
result = Lotus::Interactor::Result.new
result.prepare!(_errors: ['Error 1', 'Error 2'])
result.add_error ['Error 1', 'Error 2']

result.error.must_equal 'Error 1'
end
Expand Down

0 comments on commit f2566fd

Please sign in to comment.