Module: RubyLsp::RailsPartial::Util

Defined in:
lib/ruby_lsp/ruby_lsp_rails_partial/util.rb

Overview

AST inspection / path conversion helpers. Shared by the Definition / Completion / Hover listeners and by Addon / PartialResolver.

Constant Summary collapse

RENDER_METHODS =
%i[render render_to_string].freeze
VIEWS_MARKER =
"/app/views/"

Class Method Summary collapse

Class Method Details

.partial_string_argument(call_node) ⇒ Object

Returns the string node of the render call’s partial argument. The target is (1) the first positional argument, or (2) the value of the ‘partial:` keyword. Returns nil if neither is present.



41
42
43
44
45
46
47
48
49
# File 'lib/ruby_lsp/ruby_lsp_rails_partial/util.rb', line 41

def partial_string_argument(call_node)
  arguments = call_node.arguments&.arguments
  return unless arguments&.any?

  first = arguments.first
  return first if first.is_a?(Prism::StringNode)

  partial_keyword_value(arguments)
end

.relative_to_views(path) ⇒ Object

Returns the path relative to the app/views root. Falls back to the basename if the path is not under views.



25
26
27
28
# File 'lib/ruby_lsp/ruby_lsp_rails_partial/util.rb', line 25

def relative_to_views(path)
  index = path.index(VIEWS_MARKER)
  index ? path[(index + VIEWS_MARKER.length)..] : File.basename(path)
end

.render_call?(call_node) ⇒ Boolean

Whether call_node is a render call with no receiver (or self).

Returns:

  • (Boolean)


31
32
33
34
35
36
# File 'lib/ruby_lsp/ruby_lsp_rails_partial/util.rb', line 31

def render_call?(call_node)
  return false unless RENDER_METHODS.include?(call_node.message&.to_sym)

  receiver = call_node.receiver
  receiver.nil? || receiver.is_a?(Prism::SelfNode)
end

.uri_to_path(uri) ⇒ Object

Converts a file:// URI to a filesystem path. Non-file:// URIs are returned as-is.



15
16
17
18
19
20
21
# File 'lib/ruby_lsp/ruby_lsp_rails_partial/util.rb', line 15

def uri_to_path(uri)
  return uri unless uri.start_with?("file://")

  URI.parse(uri).path
rescue URI::InvalidURIError
  nil
end