Class: Simple::Service::Context

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

Overview

A context object

Each service executes with a current context. The system manages a stack of contexts; whenever a service execution is done the current context is reverted to its previous value.

A context object can store a large number of values; the only way to set or access a value is via getters and setters. These are implemented via method_missing(..).

Also, once a value is set in the context it is not possible to change or unset it.

Instance Method Summary collapse

Constructor Details

#initialize(hsh = {}) ⇒ Context

Returns a new instance of Context



35
36
37
# File 'lib/simple/service/context.rb', line 35

def initialize(hsh = {}) # @private
  @hsh = hsh
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object (private)

Raises:



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/simple/service/context.rb', line 59

def method_missing(sym, *args, &block)
  raise ArgumentError, "Block given" if block

  if args.count == 0 && sym =~ IDENTIFIER_REGEXP
    self[sym]
  elsif args.count == 1 && sym =~ ASSIGNMENT_REGEXP
    self[$1.to_sym] = args.first
  else
    super
  end
end

Instance Method Details

#merge(overlay) ⇒ Object

returns a new Context object, which merges the values in the overlay argument (which must be a Hash or nil) with the values in this context.

The overlay is allowed to change values in the current context.

It does not change this context.



45
46
47
48
49
50
51
# File 'lib/simple/service/context.rb', line 45

def merge(overlay)
  expect! overlay => [Hash, nil]

  overlay ||= {}
  new_context_hsh = @hsh.merge(overlay)
  ::Simple::Service::Context.new(new_context_hsh)
end