Class: Tally::KeyFinder

Inherits:
Object
  • Object
show all
Extended by:
ActiveSupport::Autoload
Defined in:
lib/tally/key_finder.rb

Overview

Locates keys for a given day, key, and/or record

Direct Known Subclasses

Daily

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key: nil, day: nil, record: nil, type: nil) ⇒ KeyFinder

Returns a new instance of KeyFinder.



13
14
15
16
17
18
19
20
# File 'lib/tally/key_finder.rb', line 13

def initialize(key: nil, day: nil, record: nil, type: nil)
  @key = key.to_s.gsub(":", ".").downcase.strip if key.present?
  @day = day
  @record = record
  @type = type unless record.present?

  @day = @day.to_date if Time === @day
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



9
10
11
# File 'lib/tally/key_finder.rb', line 9

def key
  @key
end

#recordObject (readonly)

Returns the value of attribute record.



10
11
12
# File 'lib/tally/key_finder.rb', line 10

def record
  @record
end

#typeObject (readonly)

Returns the value of attribute type.



11
12
13
# File 'lib/tally/key_finder.rb', line 11

def type
  @type
end

Class Method Details

.find(**args) ⇒ Object



64
65
66
# File 'lib/tally/key_finder.rb', line 64

def self.find(**args)
  new(**args).entries
end

Instance Method Details

#dayObject



22
23
24
# File 'lib/tally/key_finder.rb', line 22

def day
  @day ||= Time.current.utc.to_date
end

#entriesObject



26
27
28
29
30
31
32
# File 'lib/tally/key_finder.rb', line 26

def entries
  @entries ||= all_keys.map do |key|
    if match = key.match(entry_regex)
      Entry.new(match, key, day)
    end
  end.compact
end

#keysObject



34
35
36
# File 'lib/tally/key_finder.rb', line 34

def keys
  entries.map(&:key).compact.uniq
end

#raw_keysObject



38
39
40
# File 'lib/tally/key_finder.rb', line 38

def raw_keys
  all_keys
end

#recordsObject

load up all records for the given keys, tries to batch them by model type so there’s not an N+1 here



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/tally/key_finder.rb', line 44

def records
  models = entries.reduce({}) do |result, entry|
    result[entry.type] ||= []
    result[entry.type].push(entry.id)
    result
  end

  models.map do |model, ids|
    next unless ids.compact.any?

    if klass = model.to_s.classify.safe_constantize
      klass.where(id: ids)
    end
  end.compact.flatten
end

#typesObject



60
61
62
# File 'lib/tally/key_finder.rb', line 60

def types
  entries.map(&:type).compact.uniq
end