Class: Profiler::Storage::FileStore

Inherits:
BaseStore
  • Object
show all
Defined in:
lib/profiler/storage/file_store.rb

Instance Method Summary collapse

Methods inherited from BaseStore

#exists?

Constructor Details

#initialize(options = {}) ⇒ FileStore

Returns a new instance of FileStore.



11
12
13
14
15
# File 'lib/profiler/storage/file_store.rb', line 11

def initialize(options = {})
  @path = options[:path] || default_path
  @max_size = options[:max_size] || 100 * 1024 * 1024 # 100 MB
  ensure_directory_exists
end

Instance Method Details

#cleanup(older_than: 24 * 60 * 60) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/profiler/storage/file_store.rb', line 45

def cleanup(older_than: 24 * 60 * 60)
  cutoff_time = Time.now - older_than
  profile_files.each do |file|
    File.delete(file) if File.mtime(file) < cutoff_time
  rescue => e
    warn "Failed to delete profile file #{file}: #{e.message}"
  end
end

#clear(type: nil) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/profiler/storage/file_store.rb', line 67

def clear(type: nil)
  if type.nil?
    profile_files.each { |f| File.delete(f) rescue nil }
  else
    profile_files.each do |f|
      profile = load(File.basename(f, ".json"))
      File.delete(f) if profile&.profile_type == type.to_s
    rescue
      nil
    end
  end
end

#delete(token) ⇒ Object



62
63
64
65
# File 'lib/profiler/storage/file_store.rb', line 62

def delete(token)
  file_path = profile_file_path(token)
  File.delete(file_path) if File.exist?(file_path)
end

#find_by_parent(parent_token) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/profiler/storage/file_store.rb', line 54

def find_by_parent(parent_token)
  profile_files
    .map { |f| load(File.basename(f, ".json")) }
    .compact
    .select { |profile| profile.parent_token == parent_token }
    .sort_by { |profile| profile.started_at }
end

#list(limit: 50, offset: 0) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/profiler/storage/file_store.rb', line 35

def list(limit: 50, offset: 0)
  profile_files
    .sort_by { |f| File.mtime(f) }
    .reverse
    .drop(offset)
    .take(limit)
    .map { |f| load(File.basename(f, ".json")) }
    .compact
end

#load(token) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/profiler/storage/file_store.rb', line 24

def load(token)
  file_path = profile_file_path(token)
  return nil unless File.exist?(file_path)

  json_data = File.read(file_path)
  Models::Profile.from_json(json_data)
rescue => e
  warn "Failed to load profile #{token}: #{e.message}"
  nil
end

#save(token, profile) ⇒ Object



17
18
19
20
21
22
# File 'lib/profiler/storage/file_store.rb', line 17

def save(token, profile)
  file_path = profile_file_path(token)
  File.write(file_path, profile.to_json)
  cleanup_if_needed
  token
end