Implemented a keyword mechanism for theme selection.
[kaya.git] / lib / themes / loader.rb
blobb3b00d522170d0ffa825fe9306a254457f4a2998
1 class ThemeLoader
2   BASE_DIR = File.dirname(__FILE__)
3   
4   def initialize
5     # load all ruby files in subdirectories
6     Dir[File.join(BASE_DIR, '*')].each do |f|
7       if File.directory?(f)
8         Dir[File.join(f, '*.rb')].each do |rb_file|
9           require rb_file
10         end
11       end
12     end
13     
14     @themes = {}
15     ObjectSpace::each_object(Class) do |k|
16       if k.include? Theme
17         @themes[k.theme_name] = k
18       end
19     end
20     
21   end
22   
23   def each(&blk)
24     @themes.each_value(&blk)
25   end
26   
27   def get(name, game, opts = { })
28     instantiate @themes[name]
29   end
30   
31   def get_matching(preferred, game, required, optional, opts = {})
32     pref = @themes[preferred]
33     return instantiate(pref, game, opts) if pref and pref.matches?(required)
34     
35     themes = @themes.values.reject {|x| not x.matches?(required) }.sort_by {|x| x.score(optional) }
36     if themes.empty?
37       raise "No valid theme"
38     else
39       instantiate themes.last, game, opts
40     end
41   end
42   
43   private
44   
45   def instantiate(theme, game, opts = {})
46     theme.new(opts.merge(:game => game))
47   end
48 end