Upgraded Rails and RSpec
[monkeycharger.git] / vendor / rails / railties / lib / rails / plugin.rb
blobbe392195d41db83b227bdbcaf6997615f078bacb
1 module Rails
3   # The Plugin class should be an object which provides the following methods:
4   #
5   # * +name+       - used during initialisation to order the plugin (based on name and
6   #                  the contents of <tt>config.plugins</tt>)
7   # * +valid?+     - returns true if this plugin can be loaded
8   # * +load_paths+ - each path within the returned array will be added to the $LOAD_PATH
9   # * +load+       - finally 'load' the plugin.
10   #
11   # These methods are expected by the Rails::Plugin::Locator and Rails::Plugin::Loader classes.
12   # The default implementation returns the <tt>lib</tt> directory as its </tt>load_paths</tt>, 
13   # and evaluates <tt>init.rb</tt> when <tt>load</tt> is called.
14   class Plugin
15     include Comparable
16     
17     attr_reader :directory, :name
18     
19     def initialize(directory)
20       @directory = directory
21       @name = File.basename(@directory) rescue nil
22       @loaded = false
23     end
24     
25     def valid?
26       File.directory?(directory) && (has_lib_directory? || has_init_file?)
27     end
28   
29     # Returns a list of paths this plugin wishes to make available in $LOAD_PATH
30     def load_paths
31       report_nonexistant_or_empty_plugin! unless valid?
32       has_lib_directory? ? [lib_path] : []
33     end
35     # Evaluates a plugin's init.rb file
36     def load(initializer)
37       return if loaded?
38       report_nonexistant_or_empty_plugin! unless valid?
39       evaluate_init_rb(initializer)
40       @loaded = true
41     end
42     
43     def loaded?
44       @loaded
45     end
46     
47     def <=>(other_plugin)
48       name <=> other_plugin.name
49     end
50     
51     private
53       def report_nonexistant_or_empty_plugin!
54         raise LoadError, "Can not find the plugin named: #{name}"
55       end      
56     
57       def lib_path
58         File.join(directory, 'lib')
59       end
61       def init_path
62         File.join(directory, 'init.rb')
63       end
65       def has_lib_directory?
66         File.directory?(lib_path)
67       end
69       def has_init_file?
70         File.file?(init_path)
71       end
73       def evaluate_init_rb(initializer)
74          if has_init_file?
75            silence_warnings do
76              # Allow plugins to reference the current configuration object
77              config = initializer.configuration
78              
79              eval(IO.read(init_path), binding, init_path)
80            end
81          end
82       end               
83   end
84 end