Class: Pipes::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/codequest_pipes/context.rb

Overview

Context is an object used to pass data between Pipes. It behaves like an OpenStruct except you can write a value only once - this way we prevent context keys from being overwritten.

Defined Under Namespace

Classes: ExecutionTerminated, Override

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values = {}) ⇒ Context

Context constructor.

Parameters:

  • values (Hash) (defaults to: {})


19
20
21
22
# File 'lib/codequest_pipes/context.rb', line 19

def initialize(values = {})
  add(values)
  @error = nil
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error.



6
7
8
# File 'lib/codequest_pipes/context.rb', line 6

def error
  @error
end

Instance Method Details

#add(values) ⇒ Object

Method ‘add` allows adding new properties (as a Hash) to the Context.

Parameters:

  • values (Hash)


27
28
29
30
31
32
33
# File 'lib/codequest_pipes/context.rb', line 27

def add(values)
  values.each do |key, val|
    k_sym = key.to_sym
    fail Override, "Property :#{key} already present" if respond_to?(k_sym)
    define_singleton_method(k_sym) { val }
  end
end

#failure?Boolean

Check if the Context failed.

Returns:

  • (Boolean)

    Failure status.



65
66
67
# File 'lib/codequest_pipes/context.rb', line 65

def failure?
  !success?
end

#halt(error = 'Execution stopped') ⇒ Object

Quietly fail the pipe, allowing the error to be saved and accessed from the Context.

Parameters:

  • error (Any) (defaults to: 'Execution stopped')

    Error to be set.



39
40
41
# File 'lib/codequest_pipes/context.rb', line 39

def halt(error = 'Execution stopped')
  @error = error
end

#inspectString

Printable string representation of the context object_id_hex explained: stackoverflow.com/a/2818916/3526316

Returns:

  • (String)


73
74
75
76
77
78
79
# File 'lib/codequest_pipes/context.rb', line 73

def inspect
  keys = methods - Object.methods - Pipes::Context.instance_methods
  fields = keys.map { |key| "#{key}=#{public_send(key).inspect}" }
  fields << "@error=#{@error.inspect}"
  object_id_hex = '%x' % (object_id << 1)
  "#<Pipes::Context:0x00#{object_id_hex} #{fields.join(', ')}>"
end

#success?Boolean

Check if the Context finished successfully. This method smells of :reek:NilCheck

Returns:

  • (Boolean)

    Success status.



58
59
60
# File 'lib/codequest_pipes/context.rb', line 58

def success?
  @error.nil?
end

#terminate(error) ⇒ Object

Explicitly fail the pipe, allowing the error to be saved and accessed from the Context.

Parameters:

  • error (Any)

    Error to be set.

Raises:



49
50
51
52
# File 'lib/codequest_pipes/context.rb', line 49

def terminate(error)
  halt(error)
  fail ExecutionTerminated, error
end