Class: Ditz::HookManager

Inherits:
Object show all
Defined in:
lib/hook.rb

Constant Summary collapse

@@instance =
nil

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHookManager

Returns a new instance of HookManager.



3
4
5
6
# File 'lib/hook.rb', line 3

def initialize
  @descs = {}
  @blocks = {}
end

Class Method Details

.method_missing(m, *a, &b) ⇒ Object



9
10
11
12
# File 'lib/hook.rb', line 9

def self.method_missing m, *a, &b
  @@instance ||= self.new
  @@instance.send m, *a, &b
end

Instance Method Details

#enabled?(name) ⇒ Boolean

Returns:

  • (Boolean)


49
# File 'lib/hook.rb', line 49

def enabled? name; !hooks_for(name).empty? end

#hooks_for(name) ⇒ Object



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

def hooks_for name
  if @blocks[name].nil? || @blocks[name].empty?
    dirs = [Ditz::home_dir, Ditz::find_dir_containing(".ditz")].compact.map do |d|
      File.join d, ".ditz", "hooks"
    end
    Ditz::debug "looking for hooks in #{dirs.join(" and ")}"
    files = dirs.map { |d| Dir[File.join(d, "*.rb")] }.flatten
    files.each do |fn|
      Ditz::debug "loading hook file #{fn}"
      require File.expand_path(fn)
    end
  end

  @blocks[name] || []
end

#on(*names, &block) ⇒ Object



19
20
21
22
23
24
# File 'lib/hook.rb', line 19

def on *names, &block
  names.each do |name|
    raise "unregistered hook #{name.inspect}" unless @descs[name]
    @blocks[name] << block
  end
end


34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/hook.rb', line 34

def print_hooks f=$stdout
puts <<EOS
Ditz has #{@descs.size} registered hooks:

EOS

  @descs.map{ |k,v| [k.to_s,v] }.sort.each do |name, desc|
    f.puts <<EOS
#{name}
#{"-" * name.length}
#{desc}
EOS
  end
end

#register(name, desc) ⇒ Object



14
15
16
17
# File 'lib/hook.rb', line 14

def register name, desc
  @descs[name] = desc
  @blocks[name] = []
end

#run(name, *args) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/hook.rb', line 26

def run name, *args
  raise "unregistered hook #{name.inspect}" unless @descs[name]
  blocks = hooks_for name
  return false if blocks.empty?
  blocks.each { |block| block[*args] }
  true
end