Class: Rematch::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/rematch/store.rb

Overview

A simple Hash-based store that syncs with a static source map

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, source_ids) ⇒ Store

Returns a new instance of Store.



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/rematch/store.rb', line 10

def initialize(path, source_ids)
  @path    = path
  @entries = (File.exist?(path) && YAML.unsafe_load_file(path)) || {}
  # Prune dead keys (id not present ANYWHERE in the current source)
  @entries.select! { |key, _| source_ids.include?(key.split.last) }
  # Build Index: id => [key1, key2...] (FIFO queue for duplicates)
  @index = Hash.new { |h, k| h[k] = [] }
  @entries.each_key { |key| @index[key.split.last] << key }
  # Order the index queues by lineno to ensure FIFO claiming
  @index.each_value { |keys| keys.sort_by! { |k| (k) } }
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



8
9
10
# File 'lib/rematch/store.rb', line 8

def path
  @path
end

Instance Method Details

#[](key) ⇒ Object



24
# File 'lib/rematch/store.rb', line 24

def [](key)     = @entries[key]

#[]=(key, value) ⇒ Object



26
27
28
# File 'lib/rematch/store.rb', line 26

def []=(key, value)
  @entries[key] = value
end

#delete(key) ⇒ Object



23
# File 'lib/rematch/store.rb', line 23

def delete(key) = @entries.delete(key)

#pull(id) ⇒ Object

Remove and return the first key from the index id



22
# File 'lib/rematch/store.rb', line 22

def pull(id)    = @index[id].shift      # Remove and return the first key from the index id

#saveObject



30
31
32
33
34
35
36
37
38
# File 'lib/rematch/store.rb', line 30

def save
  return FileUtils.rm_f(@path) if @entries.empty?

  sorted  = @entries.sort_by { |k, _| (k) }.to_h
  content = YAML.dump(sorted, line_width: -1)
  return if File.exist?(@path) && File.read(@path) == content  # Return if unchanged (preserves mtime)

  File.write(@path, content)
end