Module: HasManyPolymorphs

Defined in:
lib/has_many_polymorphs/autoload.rb

Constant Summary collapse

DEFAULT_OPTIONS =

Searches for models that use has_many_polymorphs or acts_as_double_polymorphic_join and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes.

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 after_initialize block in config/environment.rb that appends to the 'requirements' key:

Rails::Initializer.run do |config|     
  # your other configuration here

  config.after_initialize do
    config.has_many_polymorphs_options['requirements'] << 'lib/my_extension'
  end    
end
{
:file_pattern => "#{RAILS_ROOT}/app/models/**/*.rb",
:file_exclusions => ['svn', 'CVS', 'bzr'],
:methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],
:requirements => []}
@@options =
HashWithIndifferentAccess.new(DEFAULT_OPTIONS)

Class Method Summary collapse

Class Method Details

.autoloadObject

Dispatcher callback to load polymorphic relationships from the top down.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/has_many_polymorphs/autoload.rb', line 30

def self.autoload

  _logger_debug "autoload hook invoked"
  
  options[:requirements].each do |requirement|
    _logger_warn "forcing requirement load of #{requirement}"
    require requirement
  end

  Dir.glob(options[:file_pattern]).each do |filename|
    next if filename =~ /#{options[:file_exclusions].join("|")}/
    open filename do |file|
      if file.grep(/#{options[:methods].join("|")}/).any?
        begin
          model = File.basename(filename)[0..-4].camelize
          _logger_warn "preloading parent model #{model}"
          model.constantize
        rescue Object => e
          _logger_warn "#{model} could not be preloaded: #{e.inspect}"
        end
      end
    end
  end
end