Module: RubyTorrent::EventSource

Included in:
BitTorrent, Package, PeerConnection, Piece
Defined in:
lib/rubytorrent/util.rb

Overview

“events”: very similar to Observable, but cleaner, IMO. events are listened to and sent in instance space, but registered in class space. example:

class C

include EventSource
event :goat, :boat

def send_events
  send_event :goat
  send_event(:boat, 3)
end

end

c = C.new c.on_event(:goat) { puts “got goat!” } c.on_event(:boat) { |x| puts “got boat: #x” }

Defining them in class space is not really necessary, except as an error-checking mechanism.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.append_features(mod) ⇒ Object



110
111
112
113
114
115
116
117
118
# File 'lib/rubytorrent/util.rb', line 110

def self.append_features(mod)
  super(mod)
  mod.class_eval %q{
    @@event_has ||= Hash.new(false)
    def self.event(*args)
      args.each { |a| @@event_has[a] = true }
    end
  }
end

Instance Method Details

#on_event(who, *events, &b) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/rubytorrent/util.rb', line 73

def on_event(who, *events, &b)
  @event_handlers ||= Hash.new { [] }
  events.each do |e|
    raise ArgumentError, "unknown event #{e} for #{self.class}" unless (self.class.class_eval "@@event_has")[e]
    @event_handlers[e] <<= [who, b]
  end
  nil
end

#relay_event(who, *events) ⇒ Object



100
101
102
103
104
105
106
107
108
# File 'lib/rubytorrent/util.rb', line 100

def relay_event(who, *events)
  @event_handlers ||= Hash.new { [] }
  events.each do |e|
    raise "unknown event #{e} for #{self.class}" unless (self.class.class_eval "@@event_has")[e]
    raise "unknown event #{e} for #{who.class}" unless (who.class.class_eval "@@event_has")[e]
    @event_handlers[e] <<= [who, lambda { |s, *a| who.send_event e, *a }]
  end
  nil
end

#send_event(e, *args) ⇒ Object

Raises:

  • (ArgumentError)


82
83
84
85
86
87
# File 'lib/rubytorrent/util.rb', line 82

def send_event(e, *args)
  raise ArgumentError, "unknown event #{e} for #{self.class}" unless (self.class.class_eval "@@event_has")[e]
  @event_handlers ||= Hash.new { [] }
  @event_handlers[e].each { |who, proc| proc[self, *args] }
  nil
end

#unregister_events(who, *events) ⇒ Object



89
90
91
92
93
94
95
96
97
98
# File 'lib/rubytorrent/util.rb', line 89

def unregister_events(who, *events)
  @event_handlers.each do |event, handlers|
    handlers.each do |ewho, proc|
      if (ewho == who) && (events.empty? || events.member?(event))
        @event_handlers[event].delete [who, proc]
      end
    end
  end
  nil
end