Skip to content

Commit c39b807

Browse files
committed
Allow optional: :all when deriving Inspect
1 parent a93ce08 commit c39b807

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

lib/elixir/lib/inspect.ex

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@ defprotocol Inspect do
6767
* `:optional` - (since v1.14.0) a list of fields that should not be
6868
included when they match their default value. This can be used to
6969
simplify the struct representation at the cost of hiding
70-
information.
70+
information. Since v1.19.0, the `:all` atom can be passed to
71+
mark all fields as optional.
7172
7273
Whenever `:only` or `:except` are used to restrict fields,
7374
the struct will be printed using the `#User<...>` notation,
@@ -159,11 +160,19 @@ defprotocol Inspect do
159160

160161
only = Keyword.get(options, :only, fields)
161162
except = Keyword.get(options, :except, [])
162-
optional = Keyword.get(options, :optional, [])
163163

164164
:ok = validate_option(:only, only, fields, module)
165165
:ok = validate_option(:except, except, fields, module)
166-
:ok = validate_option(:optional, optional, fields, module)
166+
167+
optional =
168+
case Keyword.get(options, :optional, []) do
169+
:all ->
170+
fields
171+
172+
optional ->
173+
:ok = validate_option(:optional, optional, fields, module)
174+
optional
175+
end
167176

168177
inspect_module =
169178
if fields == Enum.sort(only) and except == [] do

lib/elixir/test/elixir/inspect_test.exs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -772,6 +772,20 @@ defmodule Inspect.MapTest do
772772
assert inspect(struct) ==
773773
"#Inspect.MapTest.StructWithExceptOptionalAndOrder<d: nil, a: nil, ...>"
774774
end
775+
776+
defmodule StructWithOptionalAll do
777+
@derive {Inspect, optional: :all}
778+
defstruct [:a, :b, :c, :d]
779+
end
780+
781+
test "struct with :optional set to :all" do
782+
struct = %StructWithOptionalAll{a: 1, b: 2}
783+
784+
assert inspect(struct) == "%Inspect.MapTest.StructWithOptionalAll{a: 1, b: 2}"
785+
786+
struct = %StructWithOptionalAll{}
787+
assert inspect(struct) == "%Inspect.MapTest.StructWithOptionalAll{}"
788+
end
775789
end
776790

777791
defmodule Inspect.OthersTest do

0 commit comments

Comments
 (0)