Sha256: 4d17ab99311d3986b0d6a26efc04cbf1e7a21f5076eca28de7fa45dd4e335f17

Contents?: true

Size: 698 Bytes

Versions: 2

Compression:

Stored size: 698 Bytes

Contents

module Polymorph
  class Relation < SimpleDelegator

    def initialize(query, source_types:, fields:)
      @source_types, @fields = source_types, fields
      super(query)
    end

    def count
      self.to_a.length
    end

    def pluck(field)
      self.to_a.map(&field)
    end

    def where(hash = {})
      fields = hash.slice(*@fields)
      clause = fields.map do |field|
        %{(
          #{@source_types.map { |type| "#{type}.#{field[0]} = :#{field[0]}" }.join(" OR ")}
        )}
      end.join(" AND ")
      rebuild(super(clause, fields))
    end

    private

    def rebuild(query)
      self.class.new(query, source_types: @source_types, fields: @fields)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
activerecord-polymorph-0.1.2 lib/polymorph/relation.rb
activerecord-polymorph-0.1.1 lib/polymorph/relation.rb