Class: Switcher::Listener

Inherits:
Object
  • Object
show all
Defined in:
lib/switcher/listener.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Listener

Returns a new instance of Listener.



3
4
5
6
7
# File 'lib/switcher/listener.rb', line 3

def initialize(name)
  @events      = {}
  @event_names = []
  @name        = name
end

Instance Attribute Details

#event_namesObject (readonly)

Returns the value of attribute event_names.



9
10
11
# File 'lib/switcher/listener.rb', line 9

def event_names
  @event_names
end

#eventsObject (readonly)

Returns the value of attribute events.



9
10
11
# File 'lib/switcher/listener.rb', line 9

def events
  @events
end

#nameObject (readonly)

Returns the value of attribute name.



9
10
11
# File 'lib/switcher/listener.rb', line 9

def name
  @name
end

Instance Method Details

#after(event, options = {}, &block) ⇒ Object



24
25
26
27
# File 'lib/switcher/listener.rb', line 24

def after(event, options={}, &block)
  data = { callback: block, options: options }
  @events["after_#{event}"] = data
end

#before(event, options = {}, &block) ⇒ Object



11
12
13
14
15
# File 'lib/switcher/listener.rb', line 11

def before(event, options={}, &block)
  options[:allow_switch] = true
  data = { callback: block, options: options }
  @events["before_#{event}"] = data
end

#on(event, options = {}, &block) ⇒ Object



17
18
19
20
21
22
# File 'lib/switcher/listener.rb', line 17

def on(event, options={}, &block)
  options[:allow_switch] = true
  data = { callback: block, options: options }
  @event_names << event.to_sym
  @events[event.to_s] = data
end

#trigger(event, facade, instance, args) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/switcher/listener.rb', line 29

def trigger(event, facade, instance, args)
  if ev = @events[event]
    if ev[:options][:call]
      instance.instance_exec(facade, *args) { |facad, *arguments| self.send(ev[:options][:call], facad, *arguments) }
    end
    instance.instance_exec(facade, *args, &ev[:callback]) if ev[:callback].respond_to?(:call)
    if !facade.stopped && ev[:options][:allow_switch] && switch_to = ev[:options][:switch_to]
      facade.switch_to(switch_to)
    end
  end
end