|
1 | 1 | # typed: strict |
2 | 2 | # frozen_string_literal: true |
3 | 3 |
|
| 4 | +require "pathname" |
| 5 | + |
4 | 6 | module RubyLsp |
5 | 7 | module Rails |
6 | 8 | #  |
@@ -280,20 +282,26 @@ def view_template_details(arguments) |
280 | 282 | end |
281 | 283 | end |
282 | 284 |
|
| 285 | + # Determine controller name for given template path based on template |
| 286 | + # directory and view paths. |
| 287 | + # |
283 | 288 | #: (String template_path) -> String? |
284 | 289 | def controller_for_template(template_path) |
285 | | - controller_info = @client.controller("ActionController::Base") |
286 | | - return unless controller_info |
287 | | - |
288 | | - view_paths = controller_info[:view_paths] |
289 | | - template_directory = File.dirname(template_path) |
290 | | - |
291 | | - view_path = view_paths.find { |path| template_directory.start_with?(path + "/") } |
292 | | - return unless view_path |
| 290 | + template_directory = Pathname(template_path).dirname.relative_path_from(@client.rails_root) |
| 291 | + directory_segments = template_directory.each_filename.to_a |
| 292 | + possible_controller_paths = (1..directory_segments.count).map do |n| |
| 293 | + directory_segments.last(n).join("/") |
| 294 | + end |
293 | 295 |
|
294 | | - controller_path = template_directory.delete_prefix(view_path + "/") |
| 296 | + controller_path = possible_controller_paths.find do |controller_path| |
| 297 | + controller_name = camelize(controller_path) + "Controller" |
| 298 | + view_paths = @client.controller(controller_name)&.dig(:view_paths) || [] |
| 299 | + view_paths.any? do |view_path| |
| 300 | + File.join(view_path, controller_path) == File.dirname(template_path) |
| 301 | + end |
| 302 | + end |
295 | 303 |
|
296 | | - camelize(controller_path) + "Controller" |
| 304 | + camelize(controller_path) + "Controller" if controller_path |
297 | 305 | end |
298 | 306 | end |
299 | 307 | end |
|
0 commit comments