Soundcheck.Check.Warning.OptionalAttrWithoutDefault (soundcheck v0.1.0)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of normal and works with any version of Elixir.

Explanation

Flags @key reads of an optional attr that declares no default. Phoenix puts only declared defaults into a component's assigns, so when a caller omits the attr, @key raises KeyError, even inside :if={@key}.

Before:

attr :icon, :string

def badge(assigns), do: ~H"<span :if={@icon}>{@icon}</span>"

After:

attr :icon, :string, default: nil

def badge(assigns), do: ~H"<span :if={@icon}>{@icon}</span>"

Reading the attr as assigns[:icon] never raises and is not reported. Attrs marked required: true, :global attrs, keys the component body assigns before rendering (assign_new/3 included), components whose body rebinds assigns through another function, and LiveView or LiveComponent render/1 functions are skipped.

Confidence: medium. Tier: syntactic (works without compiling).

Check-Specific Parameters

Use the following parameters to configure this check:

:excluded_paths

Paths to skip (atoms, binaries as path segments, or regexes).

This parameter defaults to [~r/\/test\//, "test"].

:strict

Unused.

This parameter defaults to false.

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.