Class: FastExists::Backends::File

Inherits:
Base
  • Object
show all
Defined in:
lib/fast_exists/backends/file.rb

Instance Attribute Summary collapse

Attributes inherited from Base

#options

Instance Method Summary collapse

Methods inherited from Base

#rebuild

Constructor Details

#initialize(options = {}) ⇒ File

Returns a new instance of File.



11
12
13
14
15
16
17
18
19
# File 'lib/fast_exists/backends/file.rb', line 11

def initialize(options = {})
  super
  @file_path = options[:file_path] || FastExists.configuration.file_path || "tmp/fast_exists_#{@options[:namespace] || 'default'}.bloom"
  @filter = FastExists::Bloom::Filter.new(
    expected_elements: @expected_elements,
    false_positive_rate: @false_positive_rate
  )
  load if ::File.exist?(@file_path)
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



9
10
11
# File 'lib/fast_exists/backends/file.rb', line 9

def file_path
  @file_path
end

#filterObject (readonly)

Returns the value of attribute filter.



9
10
11
# File 'lib/fast_exists/backends/file.rb', line 9

def filter
  @filter
end

Instance Method Details

#add(key) ⇒ Object



21
22
23
24
25
# File 'lib/fast_exists/backends/file.rb', line 21

def add(key)
  res = @filter.add(key)
  save
  res
end

#capacityObject



41
42
43
# File 'lib/fast_exists/backends/file.rb', line 41

def capacity
  @filter.capacity
end

#clearObject



31
32
33
34
35
# File 'lib/fast_exists/backends/file.rb', line 31

def clear
  res = @filter.clear
  ::File.delete(@file_path) if ::File.exist?(@file_path)
  res
end

#contains?(key) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/fast_exists/backends/file.rb', line 27

def contains?(key)
  @filter.contains?(key)
end

#countObject



37
38
39
# File 'lib/fast_exists/backends/file.rb', line 37

def count
  @filter.count
end

#loadObject



56
57
58
59
60
61
62
63
# File 'lib/fast_exists/backends/file.rb', line 56

def load
  return false unless ::File.exist?(@file_path)
  data = JSON.parse(::File.binread(@file_path), symbolize_names: true)
  @filter = FastExists::Bloom::Filter.load(data)
  true
rescue => e
  raise BackendError, "Failed to load file backend: #{e.message}"
end

#saveObject



45
46
47
48
49
50
51
52
53
54
# File 'lib/fast_exists/backends/file.rb', line 45

def save
  FileUtils.mkdir_p(::File.dirname(@file_path))
  dump = @filter.dump
  temp_file = "#{@file_path}.tmp"
  ::File.binwrite(temp_file, JSON.generate(dump))
  ::File.rename(temp_file, @file_path)
  true
rescue => e
  raise BackendError, "Failed to save file backend: #{e.message}"
end

#statsObject



65
66
67
# File 'lib/fast_exists/backends/file.rb', line 65

def stats
  @filter.stats.merge(backend: :file, file_path: @file_path)
end