Sha256: 84d785ffd6b80145ac7dd85190bd59991d592f009446151d8e8846e6e0953b99

Contents?: true

Size: 1.48 KB

Versions: 19

Compression:

Stored size: 1.48 KB

Contents

# frozen_string_literal: true

module FrozenRecord
  class Index
    EMPTY_ARRAY = [].freeze
    private_constant :EMPTY_ARRAY

    AttributeNonUnique = Class.new(StandardError)

    attr_reader :attribute, :model

    def initialize(model, attribute, unique: false)
      @model = model
      @attribute = -attribute.to_s
      @index = nil
    end

    def unique?
      false
    end

    def query(matcher)
      if matcher.ranged?
        lookup_multi(matcher.value)
      else
        lookup(matcher.value)
      end
    end

    def lookup_multi(values)
      values.flat_map { |v| lookup(v) }
    end

    def lookup(value)
      @index.fetch(value, EMPTY_ARRAY)
    end

    def reset
      @index = nil
    end

    def build(records)
      @index = records.each_with_object({}) do |record, index|
        entry = (index[record[attribute]] ||= [])
        entry << record
      end
      @index.values.each(&:freeze)
      @index.freeze
    end
  end

  class UniqueIndex < Index
    def unique?
      true
    end

    def lookup_multi(values)
      results = @index.values_at(*values)
      results.compact!
      results
    end

    def lookup(value)
      record = @index[value]
      record ? [record] : EMPTY_ARRAY
    end

    def build(records)
      @index = records.each_with_object({}) { |r, index| index[r[attribute]] = r }
      if @index.size != records.size
        raise AttributeNonUnique, "#{model}##{attribute.inspect} is not unique."
      end
      @index.freeze
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
frozen_record-0.27.4 lib/frozen_record/index.rb
frozen_record-0.27.3 lib/frozen_record/index.rb
frozen_record-0.27.2 lib/frozen_record/index.rb
frozen_record-0.27.1 lib/frozen_record/index.rb
frozen_record-0.27.0 lib/frozen_record/index.rb
frozen_record-0.26.2 lib/frozen_record/index.rb
frozen_record-0.26.1 lib/frozen_record/index.rb
frozen_record-0.26.0 lib/frozen_record/index.rb
frozen_record-0.25.5 lib/frozen_record/index.rb
frozen_record-0.25.4 lib/frozen_record/index.rb
frozen_record-0.25.3 lib/frozen_record/index.rb
frozen_record-0.25.2 lib/frozen_record/index.rb
frozen_record-0.25.1 lib/frozen_record/index.rb
frozen_record-0.25.0 lib/frozen_record/index.rb
frozen_record-0.24.1 lib/frozen_record/index.rb
frozen_record-0.23.0 lib/frozen_record/index.rb
frozen_record-0.22.2 lib/frozen_record/index.rb
frozen_record-0.22.1 lib/frozen_record/index.rb
frozen_record-0.22.0 lib/frozen_record/index.rb