File tree Expand file tree Collapse file tree 2 files changed +34
-2
lines changed Expand file tree Collapse file tree 2 files changed +34
-2
lines changed Original file line number Diff line number Diff line change @@ -57,6 +57,10 @@ defmodule Inspect.Opts do
57
57
* `:inspect_fun` (since v1.9.0) - a function to build algebra documents,
58
58
defaults to `Inspect.inspect/2`
59
59
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
+
60
64
"""
61
65
62
66
# TODO: Remove :char_lists key on v2.0
@@ -71,7 +75,8 @@ defmodule Inspect.Opts do
71
75
pretty: false ,
72
76
safe: true ,
73
77
syntax_colors: [ ] ,
74
- inspect_fun: & Inspect . inspect / 2
78
+ inspect_fun: & Inspect . inspect / 2 ,
79
+ custom_options: [ ]
75
80
76
81
@ type color_key :: atom
77
82
@@ -88,7 +93,8 @@ defmodule Inspect.Opts do
88
93
pretty: boolean ,
89
94
safe: boolean ,
90
95
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
92
98
}
93
99
end
94
100
Original file line number Diff line number Diff line change @@ -679,4 +679,30 @@ defmodule Inspect.OthersTest do
679
679
assert inspect ( uri , opts ) == "#URI<https://elixir-lang.org>"
680
680
assert inspect ( [ uri ] , opts ) == "[#URI<https://elixir-lang.org>]"
681
681
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
682
708
end
You can’t perform that action at this time.
0 commit comments