All plugins load by themselves now.
[kaya.git] / lib / plugins / loader.rb
blob9562a8db09bce32e30b83d104949d2683a63219a
1 # Copyright (c) 2009 Paolo Capriotti <p.capriotti@gmail.com>
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 class PluginLoader
9   BASE_DIR = File.expand_path(File.dirname(__FILE__))
10   
11   NoPluginFound = Class.new(Exception)
12   
13   def initialize
14     # load all ruby files in subdirectories
15     Dir[File.join(BASE_DIR, '*')].each do |f|
16       if File.directory?(f)
17         Dir[File.join(f, '*.rb')].each do |rb_file|
18           load(rb_file)
19         end
20       end
21     end
22     
23     @plugins = {}
24     ObjectSpace::each_object(Class) do |k|
25       if k.include?(Plugin) and k.plugin_name
26         @plugins[k.plugin_name] = k
27       end
28     end
29   end
30   
31   def each(&blk)
32     @plugins.each_value(&blk)
33   end
34   
35   def get_matching(interface, keywords = [])
36     plugins = get_all_matching(interface).
37       sort_by {|x| x.score(keywords) }
38       
39     raise NoPluginFound if plugins.empty?
40     plugins.last
41   end
42   
43   def get_all_matching(interface)
44     @plugins.values.reject {|x| not x.implements?(interface) }
45   end
46   
47    # singleton
48   class << self
49     alias :internal_new :new
50     
51     def new
52       @instance ||= PluginLoader.internal_new
53     end
54   end
55   
56   def self.base_dir
57     BASE_DIR
58   end
59 end