Class: RubyLsp::TypeGuessr::Dsl::ArSchemaWatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_lsp/type_guessr/dsl/ar_schema_watcher.rb

Overview

Watches AR schema files (db/schema.rb, db/structure.sql) for changes and manages a disk cache for DSL-generated type data.

AR-specific: Mongoid has no schema file concept and needs a different strategy.

Constant Summary collapse

CACHE_VERSION =
1

Instance Method Summary collapse

Constructor Details

#initialize(project_root, cache_dir: nil) ⇒ ArSchemaWatcher

Returns a new instance of ArSchemaWatcher.



17
18
19
20
21
# File 'lib/ruby_lsp/type_guessr/dsl/ar_schema_watcher.rb', line 17

def initialize(project_root, cache_dir: nil)
  @project_root = project_root
  @cache_dir = cache_dir || default_cache_dir
  @last_hash = nil
end

Instance Method Details

#changed?Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
# File 'lib/ruby_lsp/type_guessr/dsl/ar_schema_watcher.rb', line 43

def changed?
  hash = current_hash
  changed = @last_hash.nil? || @last_hash != hash
  @last_hash = hash
  changed
end

#clear_cacheObject



80
81
82
# File 'lib/ruby_lsp/type_guessr/dsl/ar_schema_watcher.rb', line 80

def clear_cache
  FileUtils.rm_f(cache_path)
end

#current_hashObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ruby_lsp/type_guessr/dsl/ar_schema_watcher.rb', line 31

def current_hash
  files = schema_files
  return "empty" if files.empty?

  digest = Digest::SHA256.new
  files.each do |f|
    digest.update(f)
    digest.update(File.read(f))
  end
  digest.hexdigest
end

#load_cacheObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ruby_lsp/type_guessr/dsl/ar_schema_watcher.rb', line 50

def load_cache
  path = cache_path
  return nil unless File.exist?(path)

  data = JSON.parse(File.read(path))
  return nil unless data["version"] == CACHE_VERSION

  hash = current_hash
  return nil unless data["schema_hash"] == hash

  @last_hash = hash
  data["models"]
rescue JSON::ParserError, Errno::ENOENT
  nil
end

#save_cache(models_data) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ruby_lsp/type_guessr/dsl/ar_schema_watcher.rb', line 66

def save_cache(models_data)
  FileUtils.mkdir_p(File.dirname(cache_path))

  hash = current_hash
  data = {
    "version" => CACHE_VERSION,
    "schema_hash" => hash,
    "models" => models_data
  }

  File.write(cache_path, JSON.generate(data))
  @last_hash = hash
end

#schema_filesObject



23
24
25
26
27
28
29
# File 'lib/ruby_lsp/type_guessr/dsl/ar_schema_watcher.rb', line 23

def schema_files
  patterns = [
    File.join(@project_root, "db", "**", "schema.rb"),
    File.join(@project_root, "db", "**", "structure.sql"),
  ]
  patterns.flat_map { |p| Dir.glob(p) }.sort
end