Class: Operatic::Result

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

Direct Known Subclasses

Failure, Success

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Result

Returns a new instance of Result.

Parameters:



7
8
9
# File 'lib/operatic/result.rb', line 7

def initialize(data)
  @data = data
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, **kwargs, &block) ⇒ Object

Forwards unknown methods to its #data object allowing convenience accessors defined via Data.define to be available directly on the Operatic::Result.



76
77
78
79
# File 'lib/operatic/result.rb', line 76

def method_missing(name, *args, **kwargs, &block)
  return data.public_send(name, *args, **kwargs, &block) if data.respond_to?(name)
  super
end

Instance Attribute Details

#dataData (readonly)

Returns:



4
5
6
# File 'lib/operatic/result.rb', line 4

def data
  @data
end

Instance Method Details

#[](key) ⇒ anything

Convenience proxy to read the key from its #data object.

Parameters:

  • key (Symbol)

Returns:

  • (anything)


16
17
18
# File 'lib/operatic/result.rb', line 16

def [](key)
  data[key]
end

#deconstructArray(self, Hash<Symbol, anything>)

Returns a tuple of self and #to_h allowing you to pattern match across both the result’s status and its data.

Examples:

class SayHello
  include Operatic

  def call
    data[:message] = 'Hello world'
  end
end

case SayHello.call
in [Operatic::Success, { message: }]
  # Result is a success, do something with the `message` variable.
in [Operatic::Failure, _]
  # Result is a failure, do something else.
end

Returns:

  • (Array(self, Hash<Symbol, anything>))


40
41
42
# File 'lib/operatic/result.rb', line 40

def deconstruct
  [self, to_h]
end

#deconstruct_keys(keys = nil) ⇒ Hash<Symbol, anything>

Pattern match against the result’s data via #to_h.

Examples:

class SayHello
  include Operatic

  def call
    data[:message] = 'Hello world'
  end
end

case SayHello.call
in message:
  # Result has the `message` key, do something with the variable.
else
  # Do something else.
end

Returns:

  • (Hash<Symbol, anything>)


63
64
65
# File 'lib/operatic/result.rb', line 63

def deconstruct_keys(keys = nil)
  to_h
end

#freezeself

Returns:

  • (self)


68
69
70
71
# File 'lib/operatic/result.rb', line 68

def freeze
  data.freeze
  super
end

#respond_to?Boolean

Returns:

  • (Boolean)


81
82
83
# File 'lib/operatic/result.rb', line 81

def respond_to?(...)
  super || data.respond_to?(...)
end

#to_hHash<Symbol, anything>

Convenience proxy to Data#to_h.

Returns:

  • (Hash<Symbol, anything>)


88
89
90
# File 'lib/operatic/result.rb', line 88

def to_h
  data.to_h
end