Skip to content

Commit

Permalink
Fixes behavior of [] method for optional key
Browse files Browse the repository at this point in the history
  • Loading branch information
ivleonov committed Nov 29, 2021
1 parent 284b518 commit ee262b9
Show file tree
Hide file tree
Showing 2 changed files with 6 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 @@ -134,7 +134,11 @@ def initialize(attributes)
# rom_n_roda[:title] #=> 'Web Development with ROM and Roda'
# rom_n_roda[:subtitle] #=> nil
def [](name)
@attributes.fetch(name) { raise MissingAttributeError, name }
@attributes.fetch(name) do
next if self.class.attribute_names.include?(name)

raise MissingAttributeError, name
end
end

# Converts the {Dry::Struct} to a hash with keys representing
Expand Down
1 change: 1 addition & 0 deletions spec/integration/attributes_from_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ class Person < Dry::Struct

it "adds omittable keys" do
expect(person_without_country.country).to be_nil
expect(person_without_country[:country]).to be_nil
expect(person_with_country.country).to eql("uk")
end
end
Expand Down

0 comments on commit ee262b9

Please sign in to comment.