changelog; bugfixes for STI children (rsl)
[has_many_polymorphs.git] / lib / has_many_polymorphs / autoload.rb
blob207bc9a4f3f69ebe93563f1ee485b23d803c3ccb
2 require 'dispatcher'
4 module HasManyPolymorphs
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. 
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
20   module Autoload
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)      
31     # Override for Rails::Initializer#after_initialize.
32     def self.autoload
34       _logger_debug "autoload hook invoked"
35       
36       options[:requirements].each do |requirement|
37         require requirement
38       end
39     
40       Dir[options[:file_pattern]].each do |filename|
41         next if filename =~ /#{options[:file_exclusions].join("|")}/
42         open filename do |file|
43           if file.grep(/#{options[:methods].join("|")}/).any?
44             begin
45               model = File.basename(filename)[0..-4].camelize
46               _logger_warn "preloading parent model #{model}"
47               model.constantize
48             rescue Object => e
49               _logger_warn "WARNING; possibly critical error preloading #{model}: #{e.inspect}"
50             end
51           end
52         end
53       end
54     end  
55     
56   end
57     
58 end
60 Dispatcher.to_prepare do
61   HasManyPolymorphs::Autoload.autoload
62 end