Class: Datacaster::Result

Inherits:
Object
  • Object
show all
Defined in:
lib/datacaster/result.rb

Instance Method Summary collapse

Constructor Details

#initialize(valid, value_or_errors) ⇒ Result

Returns a new instance of Result.



3
4
5
6
7
8
9
10
# File 'lib/datacaster/result.rb', line 3

def initialize(valid, value_or_errors)
  @value_or_errors = value_or_errors
  if !valid && !@value_or_errors.is_a?(Hash) && !@value_or_errors.is_a?(Array)
    @value_or_errors = Array(@value_or_errors)
  end

  @valid = !!valid
end

Instance Method Details

#errorsObject



45
46
47
# File 'lib/datacaster/result.rb', line 45

def errors
  @errors ||= @valid ? nil : resolve_i18n(raw_errors)
end

#inspectObject



49
50
51
52
53
54
55
# File 'lib/datacaster/result.rb', line 49

def inspect
  if @valid
    "#<Datacaster::ValidResult(#{@value_or_errors.inspect})>"
  else
    "#<Datacaster::ErrorResult(#{@value_or_errors.inspect})>"
  end
end

#raw_errorsObject



41
42
43
# File 'lib/datacaster/result.rb', line 41

def raw_errors
  @valid ? nil : @value_or_errors
end

#to_dry_resultObject



57
58
59
60
61
62
63
# File 'lib/datacaster/result.rb', line 57

def to_dry_result
  if @valid
    Dry::Monads::Result::Success.new(@value_or_errors)
  else
    Dry::Monads::Result::Failure.new(errors)
  end
end

#valid?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/datacaster/result.rb', line 28

def valid?
  @valid
end

#valueObject



32
33
34
# File 'lib/datacaster/result.rb', line 32

def value
  @valid ? @value_or_errors : nil
end

#value!Object



36
37
38
39
# File 'lib/datacaster/result.rb', line 36

def value!
  raise "Tried to unwrap value of error result: #{inspect}" unless valid?
  value
end

#value_or(*values, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/datacaster/result.rb', line 12

def value_or(*values, &block)
  if values.length > 1 || (values.length == 1 && block_given?)
    raise RuntimeError, "provide either value or block: #or(value), #or { block }", caller
  end

  if valid?
    value
  else
    if values.length == 1
      values[0]
    else
      block.(errors)
    end
  end
end