Sha256: e433c9f086654801dbf2dc7afa9a7dbf7049ac11b20dff7d8f518d074844d1f6

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

class ThinkingSphinx::ActiveRecord::Polymorpher
  def initialize(source, column, class_names)
    @source, @column, @class_names = source, column, class_names
  end

  def morph!
    append_reflections
    morph_properties
  end

  private

  attr_reader :source, :column, :class_names

  def append_reflections
    mappings.each do |class_name, name|
      next if klass.reflections[name]

      reflection = clone_with name, class_name
      if ActiveRecord::Reflection.respond_to?(:add_reflection)
        ActiveRecord::Reflection.add_reflection klass, name, reflection
      else
        klass.reflections[name] = reflection
      end
    end
  end

  def clone_with(name, class_name)
    ThinkingSphinx::ActiveRecord::FilteredReflection.clone_with_filter(
      reflection, name, class_name
    )
  end

  def mappings
    @mappings ||= class_names.inject({}) do |hash, class_name|
      hash[class_name] = "#{column.__name}_#{class_name.downcase}".to_sym
      hash
    end
  end

  def morphed_stacks
    @morphed_stacks ||= mappings.values.collect { |key|
      column.__stack + [key]
    }
  end

  def morph_properties
    (source.fields + source.attributes).each do |property|
      property.rebase column.__path, :to => morphed_stacks
    end
  end

  def reflection
    @reflection ||= klass.reflections[column.__name]
  end

  def klass
    @klass ||= column.__stack.inject(source.model) { |parent, key|
      parent.reflections[key].klass
    }
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
thinking-sphinx-3.1.2 lib/thinking_sphinx/active_record/polymorpher.rb