Add the has_many_polymorphs plugin
[cs356-p2-videostore.git] / vendor / plugins / has_many_polymorphs / lib / has_many_polymorphs / autoload.rb
1
2 require 'initializer' unless defined? Rails::Initializer
3
4 class Rails::Initializer #:nodoc:
5
6 =begin rdoc    
7 Searches for models that use <tt>has_many_polymorphs</tt> or <tt>acts_as_double_polymorphic_join</tt> and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes. 
8
9 Note that you can override DEFAULT_OPTIONS via Rails::Configuration#has_many_polymorphs_options. For example, if you need an application extension to be required before has_many_polymorphs loads your models, add an <tt>after_initialize</tt> block in <tt>config/environment.rb</tt> that appends to the <tt>'requirements'</tt> key:
10   Rails::Initializer.run do |config|     
11     # your other configuration here
12     
13     config.after_initialize do
14       config.has_many_polymorphs_options['requirements'] << '/lib/my_extension'
15     end    
16   end
17   
18 =end
19
20   module HasManyPolymorphsAutoload
21         
22     DEFAULT_OPTIONS = {
23       :file_pattern => "#{RAILS_ROOT}/app/models/**/*.rb",
24       :file_exclusions => ['svn', 'CVS', 'bzr'],
25       :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],
26       :requirements => []}
27     
28     mattr_accessor :options
29     @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS)      
30
31     # Override for Rails::Initializer#after_initialize.
32     def after_initialize_with_autoload
33       after_initialize_without_autoload
34
35       _logger_debug "autoload hook invoked"
36       
37       HasManyPolymorphsAutoload.options[:requirements].each do |requirement|
38         require requirement
39       end
40     
41       Dir[HasManyPolymorphsAutoload.options[:file_pattern]].each do |filename|
42         next if filename =~ /#{HasManyPolymorphsAutoload.options[:file_exclusions].join("|")}/
43         open filename do |file|
44           if file.grep(/#{HasManyPolymorphsAutoload.options[:methods].join("|")}/).any?
45             begin
46               model = File.basename(filename)[0..-4].camelize
47               _logger_warn "preloading parent model #{model}"
48               model.constantize
49             rescue Object => e
50               _logger_warn "WARNING; possibly critical error preloading #{model}: #{e.inspect}"
51             end
52           end
53         end
54       end
55     end  
56     
57   end
58   
59   include HasManyPolymorphsAutoload
60     
61   alias_method_chain :after_initialize, :autoload
62 end