Class: Intercept::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/intercept/worker.rb

Overview

Base class of the intercept module. A worker object is responsible to intercept and modify state of registering class’s objects

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(registration_method, interceptor_map = {}, decorator_map = {}) ⇒ Worker



20
21
22
23
24
25
26
27
# File 'lib/intercept/worker.rb', line 20

def initialize(registration_method, interceptor_map = {}, decorator_map = {})
  @interceptor_map = interceptor_map
  @decorator_map = decorator_map

  if registration_method != 'intercept' && registration_method != :intercept
    define_singleton_method(registration_method) { |message| intercept(message) }
  end
end

Instance Attribute Details

#decorator_mapObject (readonly)

Returns the value of attribute decorator_map.



15
16
17
# File 'lib/intercept/worker.rb', line 15

def decorator_map
  @decorator_map
end

#interceptor_mapObject (readonly)

Returns the value of attribute interceptor_map.



15
16
17
# File 'lib/intercept/worker.rb', line 15

def interceptor_map
  @interceptor_map
end

Instance Method Details

#intercept(message) ⇒ Object

This method is called when we want to intercept and modify an object. ‘registration_method’ parameter of initialize is an alias to this method.



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/intercept/worker.rb', line 32

def intercept(message)
  interceptor_map.each do |field, strategy|
    if message.respond_to?(field) && message.respond_to?("#{field}=")
      message.public_send("#{field}=", strategy.process(message.public_send field))
    end
  end

  decorator_map.each do |field, strategy|
    if message.respond_to?(field) && message.respond_to?("#{field}=")
      message.public_send("#{field}=", strategy.decorate(message.public_send field))
    end
  end
end