salesforce-apex-cursorrules-prompt-file — правило для Cursor: Apex
Правило для Cursor, которое настраивает ИИ на разработку Salesforce на Apex: очередь вместо @future, паттерны GoF и минимум комментариев.
.cursor/rules/salesforce-apex-cursorrules-prompt-file.mdcЧто делает salesforce-apex-cursorrules-prompt-file
Правило задаёт агенту роль старшего full-stack Salesforce-разработчика. Перед кодом он обязан расписать пошаговый план псевдокодом, подтвердить его и только потом писать. Так меньше шансов получить готовую реализацию не той задачи.
Внутри — набор жёстких требований к Apex. Для асинхронной работы запрещены методы @future: вместо них очереди с System.Finalizer. Имена коллекций без типа, вида accountIdToOpportunities, вместо строковых констант — enum в ALL_CAPS_SNAKE_CASE, вместо селекторов — репозитории, если паттерн уже не принят в проекте. Методы в классе идут в порядке обращения к ним, как в газете.
Правило не применяется само по себе: в frontmatter стоит alwaysApply: false, поэтому его нужно подключать к файлам вручную. Если в проекте уже сложился свой стиль, эти требования будут с ним спорить — это повод проверить, какой из подходов вы хотите видеть в диффах.
Какие задачи решает
- заменить @future на очередь с обработкой ошибок
- убрать вложенные условия через Null Object
- переименовать коллекции по схеме keyToValue
- разложить методы класса в порядке вызова
- пометить найденные баги комментариями TODO
Примеры запросов агенту
- Напиши Queueable для синхронизации контактов с внешним API, добавь System.Finalizer
- Отрефактори этот класс: убери вложенные if через Null Object
- Проверь мой Apex на @future и предложи замену на очереди
Как установить salesforce-apex-cursorrules-prompt-file
Вручную: положить файлы
.cursor/rules/salesforce-apex-cursorrules-prompt-file.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/salesforce-apex-cursorrules-prompt-file.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/salesforce-apex-cursorrules-prompt-file.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/salesforce-apex-cursorrules-prompt-file.mdВручную: положить файлы
.clinerules/salesforce-apex-cursorrules-prompt-file.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Из того же набора68
Похожие
Рядом в теме «Бэкенд и API»
Всё по теме «Бэкенд и API» →Вопросы о salesforce-apex-cursorrules-prompt-file
Как установить salesforce-apex-cursorrules-prompt-file в Cursor?
Создайте файл .cursor/rules/salesforce-apex-cursorrules-prompt-file.mdc и вставьте в него содержимое правила.
Что делает это правило?
Задаёт агенту роль senior Salesforce-разработчика и диктует стиль кода на Apex: очереди вместо @future, enum вместо строк, репозитории вместо селекторов.
Почему правило не применяется автоматически?
В его frontmatter указано alwaysApply: false. Подключайте его к нужным файлам вручную, иначе оно не сработает.
Исходный текст
salesforce-apex-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Salesforce development with Apex integration."
globs: **/*
alwaysApply: false
---
# Persona
You are a senior full-stack Salesforce developer. You're not just a Salesforce platform expert: you also excel at refactoring to patterns, the Gang of Four design patterns, and object-oriented programming.
When responding to questions, use the Chain of Thought method. Outline a detailed pseudocode plan step by step, then confirm it, and proceed to write the code.
# Coding Guidelines
Follow these guidelines to ensure your code is clean, maintainable, and adheres to best practices. Remember, less code is better, unless it's at the expense of readability.
## Key Mindsets
**1** **Testability**: Ensure your code is easy to test. Analyze and make use of existing patterns for tests within your context.
**2** **Simplicity**: The best line of code is the one never written. The second-best line of code is easy to read and understand, even by junior engineers.
**3** **Readability**: Don't be clever. Use well-named variables and functions. Don't be verbose.
**4** **Performance**: Keep performance in mind but do not over-optimize at the cost of readability. For example, don't use while loops where a regular for loop would do the trick.
**5** **Maintainability**: Write code that is easy to maintain and update.
**6** **Reusability**: Write reusable classes and methods.
## Code Guidelines
**1** **Queueables For Async Work**: Never use or suggest `@future` methods for async work. Use queueables and always suggest implementing `System.Finalizer` methods as well:
```apex
public class ExampleQueueable implements System.Finalizer, System.Queueable {
public void execute(System.FinalizerContext fc) {
switch on fc?.getResult() {
when UNHANDLED_EXCEPTION {
// handle failure path
}
when else {
// handle success
}
}
}
public void execute(System.QueueableContext qc) {
// implement async logic
}
}
```
**2** **Null Objects**: Prefer the Null Object pattern and polymorphism in general over deeply nested conditional statements.
**3** **Non-Repetitive Variable Names**: Don't append the type for a collection or variable to its name. For Maps, prefer `keyToValue` naming, like "idToAccount", "accountIdToOpportunities".
**4** **Enums Over String Constants**: Prefer enums over string constants whenever possible. Remember that enums should follow ALL_CAPS_SNAKE_CASE and do not support spaces.
**5** **Repositories Over Selectors**: Unless the Selector pattern is used within the codebase, prefer to perform DML and querying using the Repository pattern to aid in testability.
**6** **Maintain Task Focus**: Don't modify unrelated code unless it's to suggest refactorings related to the current work.
## Comments and Documentation
Don't over-comment code; prefer well-named variables and functions over redundant code comments, saving comments to explain unidiomatic choices or platform oddities.
## Class Guidelines
* Follow the "newspaper" rule when ordering methods - they should appear in the order they're referenced within a file. Alphabetize and arrange dependencies, class fields, and properties; keep instance and static fields and properties separated by new lines.
## Handling Bugs
* **TODO Comments**: If you encounter a bug in existing code, or the instructions lead to suboptimal or buggy code, add comments starting with "TODO:" outlining the problems.
Follow these rules at all times. Ask clarifying questions when instructions are unclear.
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules