Class: Wrest::Callback

Inherits:
Object
  • Object
show all
Defined in:
lib/wrest/callback.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(callable) ⇒ Callback



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/wrest/callback.rb', line 16

def initialize(callable)
  case callable
  when Hash
    @callback_hash = Callback.ensure_values_are_collections(callable)
  when Proc
    @callback_hash = {}
    callable.call(self)
  when Callback
    @callback_hash = callable.callback_hash.dup
  end
end

Instance Attribute Details

#callback_hashObject (readonly)

Returns the value of attribute callback_hash.



14
15
16
# File 'lib/wrest/callback.rb', line 14

def callback_hash
  @callback_hash
end

Class Method Details

.ensure_values_are_collections(hash) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/wrest/callback.rb', line 62

def self.ensure_values_are_collections(hash)
  result = {}
  hash.each do |code, block|
    result[code] = block.is_a?(Array) ? block : [block]
  end
  result
end

Instance Method Details

#execute(response) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/wrest/callback.rb', line 38

def execute(response)
  callback_hash.each do |code, callback_list|
    callback_list.each { |callback| callback.call(response) } if case code
                                                                 when Range
                                                                   code.include?(response.code.to_i)
                                                                 when Integer
                                                                   code == response.code.to_i
                                                                 end
  end
end

#merge(callback) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/wrest/callback.rb', line 28

def merge(callback)
  merged_callback_hash = callback_hash.clone
  other_callback_hash = callback.callback_hash
  other_callback_hash.each do |code, callback_blocks|
    merged_callback_hash[code] ||= []
    merged_callback_hash[code] += callback_blocks
  end
  Callback.new(merged_callback_hash)
end

#on(code, &block) ⇒ Object



49
50
51
# File 'lib/wrest/callback.rb', line 49

def on(code, &block)
  @callback_hash[code] ? @callback_hash[code] << block : @callback_hash[code] = [block]
end