Class: Simple::Service::Context

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

Constant Summary collapse

IDENTIFIER_PATTERN =
"[a-z][a-z0-9_]*"
IDENTIFIER_REGEXP =
Regexp.compile("\\A#{IDENTIFIER_PATTERN}\\z")
ASSIGNMENT_REGEXP =
Regexp.compile("\\A(#{IDENTIFIER_PATTERN})=\\z")

Instance Method Summary collapse

Constructor Details

#initializeContext

Returns a new instance of Context.



3
4
5
# File 'lib/simple/service/context.rb', line 3

def initialize
  @hsh = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/simple/service/context.rb', line 27

def method_missing(sym, *args, &block)
  if block
    super
  elsif 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

#[](key) ⇒ Object



11
12
13
14
# File 'lib/simple/service/context.rb', line 11

def [](key)
  key = key.to_sym
  @hsh[key]
end

#[]=(key, value) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/simple/service/context.rb', line 16

def []=(key, value)
  key = key.to_sym
  existing_value = @hsh[key]

  unless existing_value.nil? || existing_value == value
    raise "Cannot overwrite existing context setting #{key.inspect}"
  end

  @hsh[key] = value
end

#respond_to_missing?(sym, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
# File 'lib/simple/service/context.rb', line 39

def respond_to_missing?(sym, include_private = false)
  return true if IDENTIFIER_REGEXP.maptch?(sym)
  return true if ASSIGNMENT_REGEXP.maptch?(sym)

  super
end