Class: ServiceResult

Inherits:
Object
  • Object
show all
Defined in:
lib/generators/service/install/templates/services/service_result.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeServiceResult

Returns a new instance of ServiceResult.



6
7
8
9
10
11
# File 'lib/generators/service/install/templates/services/service_result.rb', line 6

def initialize
  @value = yield
  @error = nil
rescue StandardError => e
  @error = e
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error.



4
5
6
# File 'lib/generators/service/install/templates/services/service_result.rb', line 4

def error
  @error
end

Class Method Details

.error(err) ⇒ Object



59
60
61
62
63
# File 'lib/generators/service/install/templates/services/service_result.rb', line 59

def self.error(err)
  result = allocate
  result.instance_variable_set(:@error, err)
  result
end

Instance Method Details

#ok?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/generators/service/install/templates/services/service_result.rb', line 55

def ok?
  !@error
end

#rescueObject

Raises:

  • (TypeError)


32
33
34
35
36
37
38
39
# File 'lib/generators/service/install/templates/services/service_result.rb', line 32

def rescue
  return self if ok?

  result = yield(@error)
  raise TypeError, 'block invoked in Result#rescue did not return Result' unless result.is_a?(Result)

  result
end

#thenObject

Raises:

  • (TypeError)


23
24
25
26
27
28
29
30
# File 'lib/generators/service/install/templates/services/service_result.rb', line 23

def then
  return self unless ok?

  result = yield(@value)
  raise TypeError, 'block invoked in Result#then did not return Result' unless result.is_a?(Result)

  result
end

#to_sObject Also known as: inspect



13
14
15
16
17
18
19
# File 'lib/generators/service/install/templates/services/service_result.rb', line 13

def to_s
  if ok?
    format('#<Result:0x%x value: %s>', object_id, @value.inspect)
  else
    format('#<Result:0x%x error: %s>', object_id, @error.inspect)
  end
end

#value {|@error| ... } ⇒ Object

Yields:

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
# File 'lib/generators/service/install/templates/services/service_result.rb', line 41

def value
  raise ArgumentError, 'must provide a block to Result#value to be invoked in case of error' unless block_given?

  return @value if ok?

  yield(@error)
end

#value!Object

Raises:



49
50
51
52
53
# File 'lib/generators/service/install/templates/services/service_result.rb', line 49

def value!
  raise @error unless ok?

  @value
end