File tree Expand file tree Collapse file tree 3 files changed +21
-1
lines changed Expand file tree Collapse file tree 3 files changed +21
-1
lines changed Original file line number Diff line number Diff line change 11
11
- ' 3.1 is now the minimum Ruby version (@flash-gordon)'
12
12
- ' `Dry::Struct::Error` is now a subclass of `Dry::Types::CoercionError` (in #193)
13
13
(@flash-gordon)'
14
+ - ' `Dry::Struct#[]` now returns `nil` if an optional attribute is not set.
15
+ This is consistent with calling accessor methods for optional attributes.
16
+ (issue #171 via #194) (@ivleonov + @flash-gordon)'
14
17
- version : 1.6.0
15
18
date : 2022-11-04
16
19
changed :
Original file line number Diff line number Diff line change @@ -146,7 +146,11 @@ def initialize(attributes)
146
146
# rom_n_roda[:subtitle] #=> nil
147
147
def []( name )
148
148
@attributes . fetch ( name ) do
149
- raise MissingAttributeError . new ( attribute : name , klass : self . class )
149
+ if self . class . attribute_names . include? ( name )
150
+ nil
151
+ else
152
+ raise MissingAttributeError . new ( attribute : name , klass : self . class )
153
+ end
150
154
end
151
155
end
152
156
Original file line number Diff line number Diff line change @@ -356,6 +356,19 @@ class Task < Dry::Struct
356
356
. with_message ( "Missing attribute: :name on Test::Task" )
357
357
end
358
358
359
+ describe "optional attributes" do
360
+ before do
361
+ class Test ::Task
362
+ attribute :name? , "string"
363
+ end
364
+ end
365
+
366
+ it "returns nil if the attribute is not set" do
367
+ value = Test ::Task [ user : "Jane" ]
368
+ expect ( value [ :name ] ) . to be_nil
369
+ end
370
+ end
371
+
359
372
describe "protected methods" do
360
373
before do
361
374
class Test ::Task
You can’t perform that action at this time.
0 commit comments