Skip to content

Commit bb0e8a8

Browse files
Aleksei Matiushkinjosevalim
authored andcommitted
Inspect.Opts.custom_options (#9096)
1 parent 679f978 commit bb0e8a8

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

lib/elixir/lib/inspect/algebra.ex

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ defmodule Inspect.Opts do
5757
* `:inspect_fun` (since v1.9.0) - a function to build algebra documents,
5858
defaults to `Inspect.inspect/2`
5959
60+
* `:custom_options` (since v1.9.0) - a keyword list storing custom user-defined
61+
options. Useful when implementing the `Inspect` protocol for nested structs
62+
to pass the custom options through.
63+
6064
"""
6165

6266
# TODO: Remove :char_lists key on v2.0
@@ -71,7 +75,8 @@ defmodule Inspect.Opts do
7175
pretty: false,
7276
safe: true,
7377
syntax_colors: [],
74-
inspect_fun: &Inspect.inspect/2
78+
inspect_fun: &Inspect.inspect/2,
79+
custom_options: []
7580

7681
@type color_key :: atom
7782

@@ -88,7 +93,8 @@ defmodule Inspect.Opts do
8893
pretty: boolean,
8994
safe: boolean,
9095
syntax_colors: [{color_key, IO.ANSI.ansidata()}],
91-
inspect_fun: (any, t -> Inspect.Algebra.t())
96+
inspect_fun: (any, t -> Inspect.Algebra.t()),
97+
custom_options: keyword
9298
}
9399
end
94100

lib/elixir/test/elixir/inspect_test.exs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,4 +679,30 @@ defmodule Inspect.OthersTest do
679679
assert inspect(uri, opts) == "#URI<https://elixir-lang.org>"
680680
assert inspect([uri], opts) == "[#URI<https://elixir-lang.org>]"
681681
end
682+
683+
defmodule Nested do
684+
defstruct nested: nil
685+
686+
defimpl Inspect do
687+
import Inspect.Algebra
688+
689+
def inspect(%Nested{nested: nested}, opts) do
690+
indent = Keyword.get(opts.custom_options, :indent, 2)
691+
level = Keyword.get(opts.custom_options, :level, 1)
692+
693+
nested_str =
694+
Kernel.inspect(nested, custom_options: [level: level + 1, indent: indent + 2])
695+
696+
concat(
697+
nest(line("#Nested[##{level}/#{indent}]<", nested_str), indent),
698+
nest(line("", ">"), indent - 2)
699+
)
700+
end
701+
end
702+
end
703+
704+
test "custom_options" do
705+
assert inspect(%Nested{nested: %Nested{nested: 42}}) ==
706+
"#Nested[#1/2]<\n #Nested[#2/4]<\n 42\n >\n>"
707+
end
682708
end

0 commit comments

Comments
 (0)