Elixir Cursor Rules: AI-Powered Development Best Practices

Cursor rules for Elixir development enforcing official style guides, modern Elixir 1.12+ features, and clean code principles with AI assistance for production-ready code.

Overview

Professional cursor rules for Elixir development that enforce modern standards and best practices. These rules help AI assistants generate clean, secure, and maintainable Elixir code with proper context and documentation.

Note:

Enforces official style guides, Elixir 1.12+ features, and context-aware code generation for production-ready development.

Rules Configuration

---
description: Enforces best practices for Elixir development, focusing on context-aware code generation, modern patterns, and maintainable architecture. Provides comprehensive guidelines for writing clean, efficient, and secure Elixir code with proper context.
globs: **/*.{ex,exs}
---
# Elixir Best Practices

You are an expert in Elixir programming and related technologies.
You understand modern Elixir development practices, architectural patterns, and the importance of providing complete context in code generation.

### Context-Aware Code Generation
- Always provide complete module context including imports and aliases
- Include relevant configuration files (mix.exs, config.exs) when generating projects
- Generate complete function signatures with proper parameters and guards
- Include comprehensive documentation comments explaining the purpose, parameters, and return values
- Provide context about the module's role in the larger system architecture
- Follow proper module organization and application structure

### Code Style and Structure
- Follow Elixir style guide and clean code principles
- Structure code in logical modules following domain-driven design
- Implement proper separation of concerns (contexts, schemas, services)
- Use modern Elixir features (with, for comprehensions, pattern matching) appropriately
- Maintain consistent code formatting using mix format
- Use proper module attributes and function guards
- Implement proper error handling with custom error types
- Use proper logging with structured data

### Functional Programming
- Use proper immutable data structures
- Implement proper function composition
- Use proper pattern matching
- Implement proper recursion patterns
- Use proper higher-order functions
- Implement proper data transformation
- Use proper pipe operator patterns
- Implement proper function purity

### Testing and Quality
- Write comprehensive unit tests with proper test context
- Include integration tests for critical paths
- Use proper test organization with test modules
- Implement proper test helpers and utilities
- Include performance tests for critical components
- Maintain high test coverage for core business logic
- Use proper test data factories
- Implement proper test doubles
- Use proper test organization with test attributes

### Security and Performance
- Implement proper input validation and sanitization
- Use secure authentication and token management
- Configure proper CORS and CSRF protection
- Implement rate limiting and request validation
- Use proper caching strategies
- Optimize memory usage and garbage collection
- Implement proper error handling and logging
- Use proper data validation and sanitization
- Implement proper access control

### API Design
- Follow RESTful principles with proper HTTP methods
- Use proper status codes and error responses
- Implement proper versioning strategies
- Document APIs using OpenAPI/Swagger
- Include proper request/response validation
- Implement proper pagination and filtering
- Use proper serialization and deserialization
- Implement proper rate limiting
- Use proper API authentication

### Concurrency and Distribution
- Use proper process patterns
- Implement proper message passing
- Use proper supervision trees
- Implement proper OTP patterns
- Use proper GenServer patterns
- Implement proper error handling in processes
- Use proper resource cleanup
- Implement proper backpressure
- Use proper distributed patterns

### Build and Deployment
- Use proper mix tasks and dependencies
- Implement proper CI/CD pipelines
- Use Docker for containerization
- Configure proper environment variables
- Implement proper logging and monitoring
- Use proper deployment strategies
- Implement proper backup strategies
- Use proper monitoring tools
- Implement proper error tracking

### Examples

```elixir
defmodule UserService do
  @moduledoc """
  User service module for handling user-related operations.
  Provides methods for user management and authentication.
  """

  alias UserService.{Cache, ApiClient}
  require Logger

  @doc """
  Finds a user by their email address.

  ## Parameters

    * `email` - The email address to search for

  ## Returns

    * `{:ok, user}` - If the user is found
    * `{:ok, nil}` - If the user is not found
    * `{:error, reason}` - If an error occurs
  """
  def find_user_by_email(email) when is_binary(email) do
    with {:ok, cached_user} <- check_cache(email),
         {:ok, user} <- fetch_from_api(email) do
      {:ok, user}
    else
      {:error, :not_found} -> {:ok, nil}
      {:error, reason} -> {:error, reason}
    end
  end

  defp check_cache(email) do
    case Cache.get("user:#{email}") do
      {:ok, nil} -> {:error, :not_found}
      {:ok, data} -> {:ok, Jason.decode!(data)}
      {:error, reason} -> {:error, reason}
    end
  end

  defp fetch_from_api(email) do
    case ApiClient.get_user(email) do
      {:ok, user} ->
        cache_user(user)
        {:ok, user}
      {:error, reason} ->
        Logger.error("Failed to fetch user: #{inspect(reason)}")
        {:error, reason}
    end
  end

  defp cache_user(user) do
    case Jason.encode(user) do
      {:ok, data} -> Cache.set("user:#{user.email}", data)
      {:error, reason} -> Logger.error("Failed to cache user: #{inspect(reason)}")
    end
  end
end

defmodule UserServiceTest do
  use ExUnit.Case, async: true
  alias UserService.{Cache, ApiClient}

  describe "find_user_by_email/1" do
    test "returns user when found in cache" do
      user = %{id: 1, email: "[email protected]"}
      Cache
      |> expect(:get, fn "user:[email protected]" -> {:ok, Jason.encode!(user)} end)

      assert {:ok, ^user} = UserService.find_user_by_email("[email protected]")
    end

    test "returns user when found via API" do
      user = %{id: 1, email: "[email protected]"}
      Cache
      |> expect(:get, fn "user:[email protected]" -> {:ok, nil} end)
      |> expect(:set, fn "user:[email protected]", _ -> :ok end)

      ApiClient
      |> expect(:get_user, fn "[email protected]" -> {:ok, user} end)

      assert {:ok, ^user} = UserService.find_user_by_email("[email protected]")
    end

    test "returns nil when user not found" do
      Cache
      |> expect(:get, fn "user:[email protected]" -> {:ok, nil} end)

      ApiClient
      |> expect(:get_user, fn "[email protected]" -> {:error, :not_found} end)

      assert {:ok, nil} = UserService.find_user_by_email("[email protected]")
    end

    test "returns error when API request fails" do
      Cache
      |> expect(:get, fn "user:[email protected]" -> {:ok, nil} end)

      ApiClient
      |> expect(:get_user, fn "[email protected]" -> {:error, :api_error} end)

      assert {:error, :api_error} = UserService.find_user_by_email("[email protected]")
    end
  end
end

Key Features

📦

Complete Code Context

Full module context, aliases, and docstrings included automatically

🚀

Modern Elixir 1.12+ Features

with expressions, pattern matching, and modern syntax

Testing Built-In

Automatic generation of ExUnit tests with proper mocking

🔒

Concurrency First

OTP principles, supervision trees, and process management

📐

Style Guide Compliant

Consistent code formatting following Elixir standards

🏗️

Clean Architecture

Proper separation of concerns and dependency injection

Installation

1

Choose Your IDE

Select the appropriate file path based on your development environment.

2

Create the Rules File

Create the cursor rules file in your project:

Create file: .cursor/rules/elixir.mdc

3

Add the Rules Configuration

Copy the rules configuration below into your newly created file.

4

Start Coding

Your AI assistant will now follow Elixir best practices automatically.

Use Cases

Web Applications

Full-stack Elixir applications with modern frameworks and proper architecture

API Development

RESTful APIs with proper versioning, validation, and documentation

Real-Time Systems

Scalable, concurrent systems with proper OTP patterns

Legacy Refactoring

Modernize existing Elixir codebases with current best practices

Standards Reference

StandardDescriptionEnforcement
Elixir Style GuideOfficial coding style guideAutomatic formatting
Type SafetyDialyzer specs and typespecsRequired for all functions
DocstringsComprehensive documentation blocksRequired for modules and functions
TestingExUnit test coverageAuto-generated with code
SecurityInput validation and sanitizationBuilt into patterns
ArchitectureClean separation of concernsEnforced via structure

Note:

Combine these rules with Credo and Dialyzer for maximum code quality enforcement.

Best Practices

Code Organization

  • Contexts handle business logic
  • Schemas manage data structures
  • Services contain external interactions
  • Plugs for web request pipelines

Type Safety

  • Always use typespecs for functions
  • Use Dialyzer for static analysis
  • Leverage structs for data contracts
  • Use pattern matching for validation

Testing Strategy

  • Unit tests for business logic
  • Integration tests for database operations
  • Feature tests for user workflows
  • Mocking for external dependencies

Note:

These rules work with any Elixir project but are optimized for Phoenix and Plug-based applications. Adjust framework-specific sections as needed.