Class: FrozenRecord::Index

Inherits:
Object
  • Object
show all
Defined in:
lib/frozen_record/index.rb

Direct Known Subclasses

UniqueIndex

Constant Summary collapse

AttributeNonUnique =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, attribute, unique: false) ⇒ Index

Returns a new instance of Index.



12
13
14
15
16
# File 'lib/frozen_record/index.rb', line 12

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

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



10
11
12
# File 'lib/frozen_record/index.rb', line 10

def attribute
  @attribute
end

#modelObject (readonly)

Returns the value of attribute model.



10
11
12
# File 'lib/frozen_record/index.rb', line 10

def model
  @model
end

Instance Method Details

#build(records) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/frozen_record/index.rb', line 42

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

#lookup(value) ⇒ Object



34
35
36
# File 'lib/frozen_record/index.rb', line 34

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

#lookup_multi(values) ⇒ Object



30
31
32
# File 'lib/frozen_record/index.rb', line 30

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

#query(matcher) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/frozen_record/index.rb', line 22

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

#resetObject



38
39
40
# File 'lib/frozen_record/index.rb', line 38

def reset
  @index = nil
end

#unique?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/frozen_record/index.rb', line 18

def unique?
  false
end