Sha256: dbbf8494e61c1c7cde372016afb14f046506dc5c72ba2a67a3a194e27bd777bf

Contents?: true

Size: 1.87 KB

Versions: 12

Compression:

Stored size: 1.87 KB

Contents

class ThinkingSphinx::Context
  attr_reader :indexed_models
  
  def initialize(*models)
    @indexed_models = []
  end
  
  def prepare
    ThinkingSphinx::Configuration.instance.indexed_models.each do |model|
      add_indexed_model model
    end
    
    return unless indexed_models.empty?
    
    load_models
    add_indexed_models
  end
  
  def define_indexes
    indexed_models.each { |model|
      model.constantize.define_indexes
    }
  end
  
  def add_indexed_model(model)
    model = model.name if model.is_a?(Class)
    
    indexed_models << model
    indexed_models.uniq!
    indexed_models.sort!
  end
  
  def superclass_indexed_models
    klasses = indexed_models.collect { |name| name.constantize }
    klasses.reject { |klass|
      klass.superclass.ancestors.any? { |ancestor| klasses.include?(ancestor) }
    }.collect { |klass| klass.name }
  end
  
  private
  
  def add_indexed_models
    Object.subclasses_of(ActiveRecord::Base).each do |klass|
      add_indexed_model klass if klass.has_sphinx_indexes?
    end
  end
  
  # Make sure all models are loaded - without reloading any that
  # ActiveRecord::Base is already aware of (otherwise we start to hit some
  # messy dependencies issues).
  #
  def load_models
    ThinkingSphinx::Configuration.instance.model_directories.each do |base|
      Dir["#{base}**/*.rb"].each do |file|
        model_name = file.gsub(/^#{base}([\w_\/\\]+)\.rb/, '\1')
        
        next if model_name.nil?
        next if ::ActiveRecord::Base.send(:subclasses).detect { |model|
          model.name == model_name.camelize
        }
        
        begin
          model_name.camelize.constantize
        rescue LoadError
          model_name.gsub!(/.*[\/\\]/, '').nil? ? next : retry
        rescue NameError
          next
        rescue StandardError
          STDERR.puts "Warning: Error loading #{file}"
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 6 rubygems

Version Path
joshcutler-thinking-sphinx-1.3.18 lib/thinking_sphinx/context.rb
angelf-thinking-sphinx-1.3.18 lib/thinking_sphinx/context.rb
thinking-sphinx-1.3.20 lib/thinking_sphinx/context.rb
thinking-sphinx-1.3.19 lib/thinking_sphinx/context.rb
thorsson_thinking-sphinx-1.3.18 lib/thinking_sphinx/context.rb
thinking-sphinx-allen-1.3.18.4 lib/thinking_sphinx/context.rb
thinking-sphinx-allen-1.3.18.3 lib/thinking_sphinx/context.rb
thinking-sphinx-allen-1.3.18.2 lib/thinking_sphinx/context.rb
thinking-sphinx-allen-1.3.18.1 lib/thinking_sphinx/context.rb
thinking-sphinx-allen-1.3.18 lib/thinking_sphinx/context.rb
thinking-sphinx-1.3.18 lib/thinking_sphinx/context.rb
josh_cutler-thinking-sphinx-1.3.17 lib/thinking_sphinx/context.rb