Class: Mbeditor::RubyDefinitionService

Inherits:
Object
  • Object
show all
Defined in:
app/services/mbeditor/ruby_definition_service.rb

Overview

Searches .rb files in a workspace for definitions of a named Ruby method using Ripper’s AST parser (no subprocesses).

Returns an array of hashes, each describing one definition site:

{
  file:      String,  # workspace-relative path
  line:      Integer, # 1-based line number of the `def` keyword
  signature: String,  # trimmed source text of the def line
  comments:  String   # leading # comment lines immediately above the def (may be empty)
}

Usage:

results = RubyDefinitionService.call(workspace_root, "my_method",
                                     excluded_dirnames: %w[tmp .git])

Additional class methods for IntelliSense features:

RubyDefinitionService.defs_in_file(abs_path)
  → { "method_name" => [{ line: Integer, signature: String }, ...] }
RubyDefinitionService.module_defined_in(workspace_root, "ModuleName", ...)
  → abs_path String or nil
RubyDefinitionService.includes_in_file(abs_path)
  → ["ModuleName", ...]  (include/extend/prepend calls)

Constant Summary collapse

MAX_RESULTS =
20
MAX_COMMENT_LOOKAHEAD =
15
MAX_FILES_SCANNED =
10_000

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(workspace_root, symbol, excluded_dirnames: [], excluded_paths: []) ⇒ RubyDefinitionService

Returns a new instance of RubyDefinitionService.



163
164
165
166
167
168
# File 'app/services/mbeditor/ruby_definition_service.rb', line 163

def initialize(workspace_root, symbol, excluded_dirnames: [], excluded_paths: [])
  @workspace_root   = workspace_root.to_s.chomp("/")
  @symbol           = symbol
  @excluded_dirnames = Array(excluded_dirnames)
  @excluded_paths    = Array(excluded_paths)
end

Class Attribute Details

.cache_pathObject

Returns the value of attribute cache_path.



52
53
54
# File 'app/services/mbeditor/ruby_definition_service.rb', line 52

def cache_path
  @cache_path
end

.file_cacheObject (readonly)

Returns the value of attribute file_cache.



51
52
53
# File 'app/services/mbeditor/ruby_definition_service.rb', line 51

def file_cache
  @file_cache
end

.mutexObject (readonly)

Returns the value of attribute mutex.



51
52
53
# File 'app/services/mbeditor/ruby_definition_service.rb', line 51

def mutex
  @mutex
end

Class Method Details

.call(workspace_root, symbol, excluded_dirnames: [], excluded_paths: []) ⇒ Object



54
55
56
57
58
# File 'app/services/mbeditor/ruby_definition_service.rb', line 54

def call(workspace_root, symbol, excluded_dirnames: [], excluded_paths: [])
  new(workspace_root, symbol,
      excluded_dirnames: excluded_dirnames,
      excluded_paths: excluded_paths).call
end

.clear_cache!Object

Exposed for tests.



101
102
103
104
105
106
107
# File 'app/services/mbeditor/ruby_definition_service.rb', line 101

def clear_cache!
  @mutex.synchronize { @file_cache.clear; @cache_loaded = false }
  path = @cache_path.to_s
  File.delete(path) if !path.empty? && File.exist?(path)
rescue StandardError
  nil
end

.defs_in_file(file_path) ⇒ Object

Returns all method defs in a single file from the cache (no workspace walk). The file must already be cached; returns {} if not found. Result: { “method_name” => [{ line: Integer, signature: String }, …] }



112
113
114
115
116
117
118
119
120
# File 'app/services/mbeditor/ruby_definition_service.rb', line 112

def defs_in_file(file_path)
  load_disk_cache_once
  entry = @mutex.synchronize { @file_cache[file_path.to_s] }
  return {} unless entry

  entry[:all_defs].transform_values do |lines_arr|
    lines_arr.map { |line| { line: line, signature: (entry[:lines][line - 1] || "").strip } }
  end
end

.includes_in_file(file_path) ⇒ Object

Returns the list of module/class names passed to include/extend/prepend in the given file, from the cache. The file must already be cached; returns [] if not found.



146
147
148
149
150
151
152
# File 'app/services/mbeditor/ruby_definition_service.rb', line 146

def includes_in_file(file_path)
  load_disk_cache_once
  entry = @mutex.synchronize { @file_cache[file_path.to_s] }
  return [] unless entry

  entry[:include_calls] || []
end

.load_disk_cache_onceObject

Load the JSON cache from disk exactly once per process (double-checked under the mutex so concurrent first-calls don’t double-load).



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'app/services/mbeditor/ruby_definition_service.rb', line 62

def load_disk_cache_once
  return if @cache_loaded

  @mutex.synchronize do
    return if @cache_loaded

    @cache_loaded = true
    path = @cache_path.to_s
    return if path.empty? || !File.exist?(path)

    raw = JSON.parse(File.read(path))
    raw.each do |abs_path, entry|
      @file_cache[abs_path] = {
        mtime:         entry["mtime"].to_f,
        lines:         entry["lines"],
        all_defs:      entry["all_defs"],
        module_names:  entry["module_names"],   # nil for old-format entries → triggers re-parse
        include_calls: entry["include_calls"]   # nil for old-format entries → triggers re-parse
      }
    end
  rescue StandardError
    nil # corrupted or incompatible cache file — start fresh
  end
end

.module_defined_in(workspace_root, module_name, excluded_dirnames: [], excluded_paths: []) ⇒ Object

Searches the cache (and triggers a workspace scan if needed) to find which file in workspace_root defines the given module or class name. Returns the absolute file path string or nil.



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'app/services/mbeditor/ruby_definition_service.rb', line 125

def module_defined_in(workspace_root, module_name, excluded_dirnames: [], excluded_paths: [])
  load_disk_cache_once
  result = @mutex.synchronize do
    @file_cache.find { |_path, entry| entry[:module_names]&.include?(module_name) }
  end
  return result[0] if result

  # Cache miss: scan workspace to populate cache entries with module_names.
  new(workspace_root, nil,
      excluded_dirnames: excluded_dirnames,
      excluded_paths:    excluded_paths).scan_workspace

  result = @mutex.synchronize do
    @file_cache.find { |_path, entry| entry[:module_names]&.include?(module_name) }
  end
  result ? result[0] : nil
end

.persist_cacheObject

Atomically write the in-memory cache to disk (tmp-file + rename).



88
89
90
91
92
93
94
95
96
97
98
# File 'app/services/mbeditor/ruby_definition_service.rb', line 88

def persist_cache
  path = @cache_path.to_s
  return if path.empty?

  snapshot = @mutex.synchronize { @file_cache.dup }
  tmp_path = "#{path}.tmp"
  File.write(tmp_path, JSON.generate(snapshot))
  File.rename(tmp_path, path)
rescue StandardError
  nil
end

.scan(workspace_root, excluded_dirnames: [], excluded_paths: []) ⇒ Object

Convenience wrapper: scan the whole workspace to warm the cache. Fast on subsequent calls (only re-parses files whose mtime changed).



156
157
158
159
160
# File 'app/services/mbeditor/ruby_definition_service.rb', line 156

def scan(workspace_root, excluded_dirnames: [], excluded_paths: [])
  new(workspace_root, nil,
      excluded_dirnames: excluded_dirnames,
      excluded_paths:    excluded_paths).scan_workspace
end

Instance Method Details

#callObject



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'app/services/mbeditor/ruby_definition_service.rb', line 206

def call
  self.class.load_disk_cache_once

  results       = []
  @new_entries  = false
  files_scanned = 0

  evict_deleted_cache_entries

  Find.find(@workspace_root) do |path|
    # Prune excluded directories
    if File.directory?(path)
      dirname = File.basename(path)
      rel_dir = relative_path(path)
      if path != @workspace_root && excluded_dir?(dirname, rel_dir)
        Find.prune
      end
      next
    end

    next unless path.end_with?(".rb")

    rel = relative_path(path)
    next if excluded_rel_path?(rel, File.basename(path))

    files_scanned += 1
    if files_scanned > MAX_FILES_SCANNED
      Rails.logger.warn("[mbeditor] RubyDefinitionService: workspace exceeds #{MAX_FILES_SCANNED} .rb files; stopping scan early")
      break
    end

    begin
      cached = cache_entry_for(path)
      next unless cached

      hit_lines = @symbol ? cached[:all_defs].fetch(@symbol, nil) : nil
      next unless hit_lines && hit_lines.any?

      hit_lines.each do |def_line|
        results << {
          file:      rel,
          line:      def_line,
          signature: (cached[:lines][def_line - 1] || "").strip,
          comments:  extract_comments(cached[:lines], def_line)
        }
        return results if results.length >= MAX_RESULTS
      end
    rescue StandardError
      # Malformed file or unreadable; skip silently
    end
  end

  self.class.persist_cache if @new_entries
  results
end

#scan_workspaceObject

Walks the entire workspace and populates the per-file cache (including the new module_names and include_calls fields) without filtering by symbol. Used by module_defined_in to ensure the cache is warm.



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'app/services/mbeditor/ruby_definition_service.rb', line 173

def scan_workspace
  self.class.load_disk_cache_once
  @new_entries  = false
  files_scanned = 0
  evict_deleted_cache_entries

  Find.find(@workspace_root) do |path|
    if File.directory?(path)
      dirname = File.basename(path)
      rel_dir = relative_path(path)
      Find.prune if path != @workspace_root && excluded_dir?(dirname, rel_dir)
      next
    end
    next unless path.end_with?(".rb")

    rel = relative_path(path)
    next if excluded_rel_path?(rel, File.basename(path))

    files_scanned += 1
    if files_scanned > MAX_FILES_SCANNED
      Rails.logger.warn("[mbeditor] RubyDefinitionService: workspace exceeds #{MAX_FILES_SCANNED} .rb files; stopping scan early")
      break
    end
    begin
      cache_entry_for(path)
    rescue StandardError
      nil
    end
  end

  self.class.persist_cache if @new_entries
end