Skip to content

Commit

Permalink
Update Struct#[] to return nil for unset optional attributes (fix #171
Browse files Browse the repository at this point in the history
, close #177)
  • Loading branch information
flash-gordon committed Jan 6, 2025
1 parent eb069ca commit c0f5d48
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/dry/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,11 @@ def initialize(attributes)
# rom_n_roda[:subtitle] #=> nil
def [](name)
@attributes.fetch(name) do
raise MissingAttributeError.new(attribute: name, klass: self.class)
if self.class.attribute_names.include?(name)
nil
else
raise MissingAttributeError.new(attribute: name, klass: self.class)
end
end
end

Expand Down
13 changes: 13 additions & 0 deletions spec/integration/struct_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,19 @@ class Task < Dry::Struct
.with_message("Missing attribute: :name on Test::Task")
end

describe "optional attributes" do
before do
class Test::Task
attribute :name?, "string"
end
end

it "returns nil if the attribute is not set" do
value = Test::Task[user: "Jane"]
expect(value[:name]).to be_nil
end
end

describe "protected methods" do
before do
class Test::Task
Expand Down

0 comments on commit c0f5d48

Please sign in to comment.