返回顶部
e

elixir-devElixir开发助手

Elixir/Phoenix development companion. Run and interpret mix test, mix credo, mix dialyzer, mix format. Generate modules following OTP conventions: contexts, schemas, GenServers, supervisors, tasks. Debug compilation errors and warnings. Help with Ecto migrations, queries, changesets, and associations. Use for any Elixir or Phoenix development task including writing modules, fixing tests, refactoring code, or understanding OTP patterns.

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.0.0
安全检测
已通过
1,902
下载量
免费
免费
1
收藏
概述
安装方式
版本历史

elixir-dev

Elixir Dev

运行 Mix 命令

完整命令参考请参见 references/mix-commands.md

测试

bash

运行所有测试


mix test

指定文件或行号

mix test test/myapp/accountstest.exs:42

按标签运行

mix test --only integration

仅运行上次失败的测试(需先使用 --failed 标志)

mix test --failed

带覆盖率报告

mix test --cover

失败原因解读:

  • - (MatchError) — 模式匹配失败;检查返回值结构。
  • (Ecto.NoResultsError) — Repo.get! 查询不存在的 ID;改用 Repo.get 或填充种子数据。
  • (DBConnection.OwnershipError) — 缺少 async: true 或沙箱配置。
  • no function clause matching — 参数数量错误或参数类型不符合预期。

Credo

bash
mix credo --strict
mix credo suggest --format json
mix credo explain MyApp.Module # 解释特定模块的问题

常见 Credo 修复:

  • - Credo.Check.Readability.ModuleDoc — 添加 @moduledoc。
  • Credo.Check.Refactor.CyclomaticComplexity — 提取辅助函数。
  • Credo.Check.Design.TagTODO — 处理或删除 TODO 注释。

Dialyzer

bash
mix dialyzer
mix dialyzer --format short

常见 Dialyzer 警告:

  • - The pattern can never match — 死代码或模式中的类型错误。
  • Function has no local return — 所有路径都会崩溃;检查内部调用。
  • The call will never return — 调用了始终会抛出异常的函数。
  • 修复方法:添加 @spec 注解;最后手段使用 @dialyzer {:nowarn_function, func: arity}。

格式化

bash
mix format
mix format --check-formatted # CI 模式 — 未格式化则退出码为 1

模块生成

始终在公共函数上包含 @moduledoc、@doc 和 @spec。

上下文模块

elixir
defmodule MyApp.Notifications do
@moduledoc
管理通知投递和偏好设置。

import Ecto.Query
alias MyApp.Repo
alias MyApp.Notifications.Notification

@doc 列出用户的通知,按最新时间排序。
@spec list_notifications(String.t(), keyword()) :: [Notification.t()]
def listnotifications(userid, opts \\ []) do
limit = Keyword.get(opts, :limit, 50)

Notification
|> where(userid: ^userid)
|> orderby(desc: :insertedat)
|> limit(^limit)
|> Repo.all()
end
end

模式模块

elixir
defmodule MyApp.Notifications.Notification do
@moduledoc
推送/邮件/短信通知的模式。

use Ecto.Schema
import Ecto.Changeset

@type t :: %MODULE{}

@primarykey {:id, :binaryid, autogenerate: true}
@foreignkeytype :binary_id
@timestampsopts [type: :utcdatetime_usec]

schema notifications do
field :channel, Ecto.Enum, values: [:push, :email, :sms]
field :title, :string
field :body, :string
field :deliveredat, :utcdatetime_usec
field :userid, :binaryid

timestamps()
end

@required ~w(channel title body user_id)a

@doc false
def changeset(notification, attrs) do
notification
|> cast(attrs, @required ++ [:delivered_at])
|> validate_required(@required)
|> validate_length(:title, max: 255)
end
end

OTP 模式

GenServer、Supervisor、Agent、Task 模式请参见 references/otp-patterns.md

何时使用何种模式

模式使用场景
GenServer带同步/异步调用的有状态进程(缓存、限流器、连接池)
Agent
简单的状态封装,无需复杂逻辑 | | Task | 一次性异步工作,即发即忘或等待结果 | | Task.Supervisor | 受监督的即发即忘任务 | | Supervisor | 管理子进程生命周期 | | Registry | 按名称/键查找进程 | | DynamicSupervisor | 运行时启动子进程 |

GenServer 模板

elixir
defmodule MyApp.RateLimiter do
@moduledoc 令牌桶限流器。
use GenServer

# 客户端 API
def start_link(opts) do
name = Keyword.get(opts, :name, MODULE)
GenServer.start_link(MODULE, opts, name: name)
end

@spec checkrate(String.t()) :: :ok | {:error, :ratelimited}
def check_rate(key), do: GenServer.call(MODULE, {:check, key})

# 服务端回调
@impl true
def init(opts) do
{:ok, %{limit: Keyword.get(opts, :limit, 100), windowms: 60000, buckets: %{}}}
end

@impl true
def handlecall({:check, key}, from, state) do
now = System.monotonic_time(:millisecond)
{count, state} = increment(state, key, now)
if count <= state.limit, do: {:reply, :ok, state}, else: {:reply, {:error, :rate_limited}, state}
end

defp increment(state, key, now) do
# 实现代码
end
end

常见编译错误

错误原因修复方法
module X is not available缺少依赖或拼写错误检查 mix.exs 依赖,验证模块名称
undefined function X/N
未导入或未别名 | 添加 import、alias 或完整模块路径 | | (CompileError) redefining module | 模块名重复 | 重命名其中一个 | | protocol not implemented | 缺少协议实现 | 为结构体添加 defimpl | | cannot use ^x outside of match | 插值位置错误 | 移到模式匹配上下文中 |

Ecto 查询模式

动态筛选

elixir
def list(filters) do
Enum.reduce(filters, base_query(), fn
{:status, val}, q -> where(q, [r], r.status == ^val)
{:since, dt}, q -> where(q, [r], r.inserted_at >= ^dt)
{:search, term}, q -> where(q, [r], ilike(r.name, ^%#{term}%))
_, q -> q
end)
|> Repo.all()
end

预加载

elixir

查询时预加载(单查询带连接)


from(p in Post, join: a in assoc(p, :author), preload: [author: a])

独立查询预加载

Post |> Repo.all() |> Repo.preload(:author)

嵌套预加载

Repo.preload(posts, [comments: :author])

聚合查询

elixir
from(o in Order,
where: o.tenantid == ^tenantid,
group_by: o.status,
select: {o.status, count(o.id), sum(o.amount)}
)
|> Repo.all()

Phoenix LiveView 基础

挂载 + 事件处理

elixir
defmodule MyAppWeb.DashboardLive do
use MyAppWeb, :live_view

@impl true
def mount(params, session, socket) do
{:ok, assign(socket, items: [], loading: true)}
end

@impl true
def handle_event(delete, %{id => id}, socket) do
MyApp.Items.delete_item!(id)
{:noreply, assign(socket, items: MyApp.Items.list_items())}
end

@impl true
def render(assigns) do
~H


<%= item.name %>

end
end

###

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 elixir-dev-1776368300 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 elixir-dev-1776368300 技能

通过命令行安装

skillhub install elixir-dev-1776368300

下载

⬇ 下载 elixir-dev v1.0.0(免费)

文件大小: 7.62 KB | 发布时间: 2026-4-17 16:09

v1.0.0 最新 2026-4-17 16:09
Initial release of elixir-dev: a comprehensive Elixir/Phoenix development companion.

- Run and interpret `mix` commands: test, credo, dialyzer, format.
- Generate modules with OTP conventions—contexts, schemas, GenServers, supervisors, and tasks.
- Debug compilation errors and warnings; get quick explanations and fixes.
- Get help with Ecto migrations, queries, changesets, and associations.
- Reference practical templates and patterns for OTP, Ecto, and Phoenix LiveView tasks.

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部