Class: ValueOrException

Inherits:
Object show all
Defined in:
lib/value_or_exception.rb

Overview

ValueOrException

Encapsulates either a valid String value or an exception Symbol, and provides methods to query and update the stored value.

Examples

obj = ValueOrException.new("foo")
obj.valid?       # => true
obj.exception?   # => false
obj.get          # => "foo"

obj.set(:error)  # now holds an exception
obj.valid?       # => false
obj.exception?   # => true
obj.get          # => :error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(val, message = nil) ⇒ ValueOrException

Returns a new instance of ValueOrException.

Parameters:

  • val (String, Symbol)

    a valid string or an exception symbol

Raises:

  • (ArgumentError)

    if val is neither String nor Symbol



29
30
31
32
33
# File 'lib/value_or_exception.rb', line 29

def initialize(val, message = nil)
  validate!(val)
  @value = val
  @message = message
end

Instance Attribute Details

#messageString, Symbol

Returns the stored value or exception.

Returns:

  • (String, Symbol)

    the stored value or exception



24
25
26
# File 'lib/value_or_exception.rb', line 24

def message
  @message
end

#valueObject (readonly)

Returns the value of attribute value.



25
26
27
# File 'lib/value_or_exception.rb', line 25

def value
  @value
end

Instance Method Details

#exception?Boolean

Returns true if the stored value is a Symbol (an exception).

Returns:

  • (Boolean)

    true if the stored value is a Symbol (an exception)



36
37
38
# File 'lib/value_or_exception.rb', line 36

def exception?
  value.is_a?(Symbol)
end

#getString, Symbol

Retrieve the current stored value or exception.

Returns:



48
49
50
# File 'lib/value_or_exception.rb', line 48

def get
  valid? ? value : message
end

#set(new_val) ⇒ Object

Update the stored value or exception.

Parameters:

  • new_val (String, Symbol)

    the new value or exception

Raises:

  • (ArgumentError)

    if new_val is neither String nor Symbol



56
57
58
59
# File 'lib/value_or_exception.rb', line 56

def set(new_val)
  validate!(new_val)
  @value = new_val
end

#to_sObject



61
62
63
# File 'lib/value_or_exception.rb', line 61

def to_s
  valid? ? value.to_s : message
end

#valid?Boolean

Returns true if the stored value is a String (a valid value).

Returns:

  • (Boolean)

    true if the stored value is a String (a valid value)



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

def valid?
  !exception?
end