Contexted.CRUD (contexted v0.3.2)

The Contexted.CRUD module generates common CRUD (Create, Read, Update, Delete) functions for a context, similar to what mix phx gen context task generates.

options

Options

  • :repo - The Ecto repository module used for database operations (required)
  • :schema - The Ecto schema module representing the resource that these CRUD operations will be generated for (required)
  • :exclude - A list of atoms representing the functions to be excluded from generation (optional)
  • :plural_resource_name - A custom plural version of the resource name to be used in function names (optional). If not provided, singular version with 's' ending will be used to generate list function

usage

Usage

defmodule MyApp.Accounts do
  use Contexted.CRUD,
    repo: MyApp.Repo,
    schema: MyApp.Accounts.User,
    exclude: [:delete],
    plural_resource_name: "users"
end

This sample usage will generate all CRUD functions for MyApp.Accounts.User resource, excluding delete_user/1.

generated-functions

Generated Functions

The following functions are generated by default. Any of them can be excluded by adding their correspoding atom to the :exclude option.

  • list_{plural resource name} - Lists all resources in the schema.
  • get_{resource name} - Retrieves a resource by its ID. Returns nil if not found.
  • get_{resource name}! - Retrieves a resource by its ID. Raises an error if not found.
  • create_{resource name} - Creates a new resource with the provided attributes. Returns an :ok tuple with the resource or an :error tuple with changeset.
  • create_{resource name}! - Creates a new resource with the provided attributes. Raises an error if creation fails.
  • update_{resource name} - Updates an existing resource with the provided attributes. Returns an :ok tuple with the resource or an :error tuple with changeset.
  • update_{resource name}! - Updates an existing resource with the provided attributes. Raises an error if update fails.
  • delete_{resource name} - Deletes an existing resource. Returns an :ok tuple with the resource or an :error tuple with changeset.
  • delete_{resource name}! - Deletes an existing resource. Raises an error if delete fails.
  • change_{resource name} - Returns changeset for given resource.

{resource name} and {plural resource name} will be replaced by the singular and plural forms of the resource name.