Module: Unobservable

Defined in:
lib/unobservable.rb

Defined Under Namespace

Modules: ModuleSupport, Support Classes: Event

Class Method Summary collapse

Class Method Details

.collect_instance_events_defined_by(contributors) ⇒ Object

Produces a list of instance events that are explicitly defined by at least one of the specified modules.



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/unobservable.rb', line 30

def self.collect_instance_events_defined_by(contributors)
  retval = Set.new
  
  contributors.each do |c|
    if c.instance_variable_defined? :@unobservable_instance_events
      c.instance_variable_get(:@unobservable_instance_events).each do |e|
        retval.add(e)
      end
    end
  end
  
  return retval.to_a
end

.handler_for(*args, &block) ⇒ Object

There are 3 ways for end-users to provide an event handler:

  1. They can pass an object that has a #call method

  2. They can provide an object and the name of a method to invoke

  3. They can pass in a block

Raises:

  • (ArgumentError)


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/unobservable.rb', line 50

def self.handler_for(*args, &block)
  if block
    return block
  elsif args.size == 1
    candidate = args[0]
    if candidate.respond_to?(:to_proc)
      return candidate.to_proc
    else
      raise ArgumentError, "The argument does not respond to the #to_proc method"
    end
  elsif args.size == 2
    return args[0].method(args[1])
  end

  raise ArgumentError, "Unable to create an event handler using the given arguments"
end

.instance_events_for(mod, all = true) ⇒ Object

Produces a list of instance events for any module regardless of whether or not that module includes the Unobservable::ModuleSupport mixin. If include_supers = true, then the list will also contain instance events defined by superclasses and included modules. By default, include_supers = true

Raises:

  • (TypeError)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/unobservable.rb', line 9

def self.instance_events_for(mod, all = true)
  raise TypeError, "Only modules and classes can have instance_events" unless mod.is_a? Module

  contributors = [mod]
  if all
    contributors += mod.included_modules
    if mod.is_a? Class
      parent = mod.superclass
      while parent
        contributors.push parent
        parent = parent.superclass
      end
    end
  end

  self.collect_instance_events_defined_by(contributors)
end