Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai b1ad997047 feat(rails): go to declaration from callback symbols and routes
Go to Declaration (and ⌘-click) on a method symbol in a callback
(before_action :load_user, skip_before_action, helper_method, validate,
if: :admin?) opens its def in the class, or in ApplicationController /
ApplicationRecord. In config/routes.rb, "controller#action" strings open the
action's def and resources / resource symbols open the controller.

Refs #900
2026-11-16 15:01:13 +08:00
5 змінених файлів з 152 додано та 4 видалено

No files matched your search

+1
Переглянути файл
@@ -61,6 +61,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
- Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there.
- **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none.
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations. With several targets it shows a chooser.
- In Rails, **Go to Declaration** also follows method symbols in callbacks (`before_action :load_user`, `if: :admin?`) to their `def`, and controller actions in `config/routes.rb` (`to: "users#index"`, `resources :users`) to the controller.
Going to files, classes and symbols by name is covered in [Search and navigation](/en/guide/search).
+1
Переглянути файл
@@ -61,6 +61,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
- 装订区域的图标标出被实现或被重写的类型和方法(↓),以及实现或重写了其他方法的方法(↑),单击即可跳转。
- **导航 › 测试** 按命名约定在类和它的测试之间跳转;还没有测试时会提供 **创建新测试…**。
- **导航 › 相关符号…** 跳到按约定与当前文件相关的文件:C、C++、Objective-C 的头文件和源文件,以及 Rails 中控制器动作与其视图、视图与其动作、控制器与其辅助模块和模型、模型与其控制器和迁移。有多个目标时显示选择列表。
- 在 Rails 中,**转到声明** 还能从回调里的方法符号(`before_action :load_user`、`if: :admin?`)跳到对应的 `def`,从 `config/routes.rb` 里的控制器动作(`to: "users#index"`、`resources :users`)跳到控制器。
按名称跳转到文件、类和符号,见 [搜索与导航](/zh/guide/search)。
+54 -4
Переглянути файл
@@ -1,8 +1,16 @@
/** Rails: Navigate › Related Symbol between controllers, actions, views, helpers, models and migrations. */
/**
* Rails: Navigate › Related Symbol between controllers, actions, views, helpers, models and
* migrations; Go to Declaration on callback method symbols and on routes' controller actions.
*/
import { Text } from "@codemirror/state";
import { docOf } from "@/editor/lsp/lsp";
import { offsetsToRange } from "@/editor/lsp/positions";
import { registerNavigationProvider } from "@/editor/navigationProviders";
import { registerRelatedProvider } from "@/editor/relatedProviders";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { railsTargets, type RailsFs, type RailsGroup } from "./conventions";
import { call, commands, type Location } from "@/platform/ipc";
import { controllerName, defLine, railsTargets, type RailsFs, type RailsGroup } from "./conventions";
import { railsReferenceAt } from "./references";
const fs: RailsFs = {
list: async (dir) => {
@@ -29,9 +37,51 @@ const GROUPS: Record<RailsGroup, () => string> = {
migration: () => tx("Migration"),
};
/** The `def name` in `text` as a navigation target, at the method name. */
function method(path: string, text: string, name: string, label?: string): (Location & { name?: string }) | null {
const line = defLine(text, name);
if (line === undefined) return null;
const doc = Text.of(text.split("\n"));
const at = doc.line(line + 1);
const col = at.text.indexOf(name, at.text.indexOf("def") + 3);
return { path, range: offsetsToRange(doc, at.from + col, at.from + col + name.length), name: label };
}
const ROUTES = /\/config\/routes(?:\/[^/]+)?\.rb$/;
export function activate(): () => void {
return registerRelatedProvider(async (ctx) => {
const unregisterRelated = registerRelatedProvider(async (ctx) => {
const targets = await railsTargets(ctx.path, ctx.text, ctx.offset, fs);
return targets.map((t) => ({ path: t.path, line: t.line, label: t.label, group: GROUPS[t.group]() }));
});
const unregisterNavigation = registerNavigationProvider(async (view, offset) => {
const doc = docOf(view);
if (!doc || doc.virtual || !doc.path.endsWith(".rb")) return null;
const routes = ROUTES.exec(doc.path);
const text = view.state.doc.toString();
const ref = railsReferenceAt(text, offset, !!routes);
if (!ref) return null;
if (ref.kind === "method") {
const own = method(doc.path, text, ref.name);
const app = doc.path.match(/^(.*)\/app\/(controllers|models)\//);
const base =
app && !own ? `${app[1]}/app/${app[2]}/application_${app[2] === "models" ? "record" : "controller"}.rb` : null;
const baseText = base ? await fs.read(base) : null;
const target = own ?? (base && baseText !== null ? method(base, baseText, ref.name) : null);
return target ? { from: ref.from, to: ref.to, targets: [target] } : null;
}
const root = doc.path.slice(0, routes!.index);
const path = `${root}/app/controllers/${ref.resource}_controller.rb`;
const controller = await fs.read(path);
if (controller === null) return null;
const name = controllerName(ref.resource);
const target = ref.action
? method(path, controller, ref.action, `${name}#${ref.action}`)
: { path, range: offsetsToRange(Text.of([""]), 0, 0), name };
return target ? { from: ref.from, to: ref.to, targets: [target] } : null;
});
return () => {
unregisterNavigation();
unregisterRelated();
};
}
+34
Переглянути файл
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { railsReferenceAt } from "./references";
const at = (text: string, routes = false) => railsReferenceAt(text.replace("|", ""), text.indexOf("|"), routes);
describe("rails references", () => {
it("reads method symbols in callbacks", () => {
expect(at(" before_action :load_|user, only: [:show]")).toEqual({
kind: "method",
name: "load_user",
from: 17,
to: 26,
});
expect(at(" before_action :load_user, if: :ad|min?")).toMatchObject({ name: "admin?" });
expect(at(" skip_before_action :auth|enticate!")).toMatchObject({ name: "authenticate!" });
expect(at(" helper_method :current|_user")).toMatchObject({ name: "current_user" });
expect(at(" validate :email_|format")).toMatchObject({ name: "email_format" });
expect(at(" has_many :po|sts")).toBeNull();
expect(at(" before_action Foo::Ba|r")).toBeNull();
});
it("reads controller actions in routes", () => {
expect(at(' get "login", to: "sess|ions#new"', true)).toMatchObject({ resource: "sessions", action: "new" });
expect(at(" get '/x' => 'admin/rep|orts#index'", true)).toMatchObject({
resource: "admin/reports",
action: "index",
});
expect(at(" resources :pho|tos", true)).toMatchObject({ resource: "photos", action: null });
expect(at(" resources :users, :pos|ts", true)).toMatchObject({ resource: "posts" });
expect(at(" resource :prof|ile", true)).toMatchObject({ resource: "profiles" });
expect(at(" root 'pages#ho|me'", true)).toMatchObject({ resource: "pages", action: "home" });
expect(at(" mount Sidekiq::W|eb", true)).toBeNull();
});
});
+62
Переглянути файл
@@ -0,0 +1,62 @@
/**
* Rails references navigated with Go to Declaration: method symbols in callbacks
* (`before_action :load_user`, `if: :admin?`) and controller actions in `config/routes.rb`
* (`to: "users#index"`, `resources :users`).
*/
import { pluralize } from "./conventions";
export type RailsReference =
| { kind: "method"; name: string; from: number; to: number }
| { kind: "action"; resource: string; action: string | null; from: number; to: number };
/** Class-level calls whose symbol arguments name methods of the class. */
const CALLBACK =
/^\s*(?:(?:prepend|append|skip)_)?(?:before|after|around)_[a-z_]+\b|^\s*(?:helper_method|validate|rescue_from|after_commit|after_rollback)\b/;
const SYMBOL = /(^|[^\w:]):([A-Za-z_]\w*[!?]?)/g;
const ACTION_STRING = /(["'])((?:[a-z0-9_]+\/)*[a-z0-9_]+)#([a-z_]\w*[!?]?)\1/g;
const RESOURCES = /^\s*(resources?)\s+((?::[a-z_]\w*\s*,\s*)*:[a-z_]\w*)/;
function lineAt(text: string, offset: number): { line: string; start: number } {
const start = text.lastIndexOf("\n", offset - 1) + 1;
const end = text.indexOf("\n", offset);
return { line: text.slice(start, end < 0 ? text.length : end), start };
}
export function railsReferenceAt(text: string, offset: number, routes: boolean): RailsReference | null {
const { line, start } = lineAt(text, offset);
const col = offset - start;
if (routes) {
for (const m of line.matchAll(ACTION_STRING)) {
if (col > m.index && col < m.index + m[0].length - 1)
return {
kind: "action",
resource: m[2]!,
action: m[3]!,
from: start + m.index + 1,
to: start + m.index + m[0].length - 1,
};
}
const r = RESOURCES.exec(line);
if (r) {
for (const s of r[2]!.matchAll(/:([a-z_]\w*)/g)) {
const from = r.index + r[0].length - r[2]!.length + s.index;
if (col >= from && col < from + s[0].length)
return {
kind: "action",
resource: r[1] === "resource" ? pluralize(s[1]!) : s[1]!,
action: null,
from: start + from + 1,
to: start + from + s[0].length,
};
}
}
return null;
}
if (!CALLBACK.test(line)) return null;
for (const m of line.matchAll(SYMBOL)) {
const at = m.index + m[1]!.length;
if (col >= at && col < m.index + m[0].length)
return { kind: "method", name: m[2]!, from: start + at + 1, to: start + m.index + m[0].length };
}
return null;
}