Class: RubyLsp::Requests::CodeActions

Inherits:
Request
  • Object
show all
Defined in:
lib/ruby_lsp/requests/code_actions.rb

Overview

The [code actions](microsoft.github.io/language-server-protocol/specification#textDocument_codeAction) request informs the editor of RuboCop quick fixes that can be applied. These are accessible by hovering over a specific diagnostic.

Constant Summary collapse

EXTRACT_TO_VARIABLE_TITLE =
"Refactor: Extract Variable"
EXTRACT_TO_METHOD_TITLE =
"Refactor: Extract Method"
TOGGLE_BLOCK_STYLE_TITLE =
"Refactor: Toggle block style"
CREATE_ATTRIBUTE_READER =
"Create Attribute Reader"
CREATE_ATTRIBUTE_WRITER =
"Create Attribute Writer"
CREATE_ATTRIBUTE_ACCESSOR =
"Create Attribute Accessor"
INSTANCE_VARIABLE_NODES =
[
  Prism::InstanceVariableAndWriteNode,
  Prism::InstanceVariableOperatorWriteNode,
  Prism::InstanceVariableOrWriteNode,
  Prism::InstanceVariableReadNode,
  Prism::InstanceVariableTargetNode,
  Prism::InstanceVariableWriteNode,
]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document, range, context) ⇒ CodeActions

: ((RubyDocument | ERBDocument) document, Hash[Symbol, untyped] range, Hash[Symbol, untyped] context) -> void



37
38
39
40
41
42
43
# File 'lib/ruby_lsp/requests/code_actions.rb', line 37

def initialize(document, range, context)
  super()
  @document = document
  @uri = document.uri #: URI::Generic
  @range = range
  @context = context
end

Class Method Details

.providerObject

: -> Interface::CodeActionRegistrationOptions



28
29
30
31
32
33
# File 'lib/ruby_lsp/requests/code_actions.rb', line 28

def provider
  Interface::CodeActionRegistrationOptions.new(
    document_selector: nil,
    resolve_provider: true,
  )
end

Instance Method Details

#performObject

: -> (Array & Object)?



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/ruby_lsp/requests/code_actions.rb', line 47

def perform
  diagnostics = @context[:diagnostics]

  code_actions = diagnostics.flat_map do |diagnostic|
    diagnostic.dig(:data, :code_actions) || []
  end

  # Only add refactor actions if there's a non empty selection in the editor
  unless @range.dig(:start) == @range.dig(:end)
    code_actions << Interface::CodeAction.new(
      title: EXTRACT_TO_VARIABLE_TITLE,
      kind: Constant::CodeActionKind::REFACTOR_EXTRACT,
      data: { range: @range, uri: @uri.to_s },
    )
    code_actions << Interface::CodeAction.new(
      title: EXTRACT_TO_METHOD_TITLE,
      kind: Constant::CodeActionKind::REFACTOR_EXTRACT,
      data: { range: @range, uri: @uri.to_s },
    )
    code_actions << Interface::CodeAction.new(
      title: TOGGLE_BLOCK_STYLE_TITLE,
      kind: Constant::CodeActionKind::REFACTOR_REWRITE,
      data: { range: @range, uri: @uri.to_s },
    )
  end
  code_actions.concat(attribute_actions)

  code_actions
end