Class: EM::Udev

Inherits:
Object
  • Object
show all
Defined in:
lib/eventmachine/udev.rb

Class Method Summary collapse

Class Method Details

.new(handler) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/eventmachine/udev.rb', line 25

def self.new (handler)
  context = RubDev::Context.new
  monitor = RubDev::Monitor.from_netlink(context, 'udev')

  mod = Module.new {
    include handler if handler

    define_method(:device_added) {|dev|
      puts "added #{dev.devnode}"
    } unless instance_methods.include?(:device_added)

    define_method(:device_removed) {|dev|
      puts "removed #{dev.devnode}"
    } unless instance_methods.include?(:device_removed)

    define_method(:notify_readable) {
      dev = monitor.receive_device
      self.send((dev.action == 'add' ? :device_added : :device_removed), dev)
    } unless instance_methods.include?(:notify_readable)
  }

  EM.watch(monitor.to_io, mod).tap {|c|
    [[:@context, context], [:@monitor, monitor]].each {|args|
      c.instance_variable_set(*args)
    }

    c.notify_readable = true
    monitor.enable_receiving
  }
end