Skip to content

Commit

Permalink
fix: mimic JS behavior for delete(obj.foo)
Browse files Browse the repository at this point in the history
  • Loading branch information
0x1eef committed Mar 28, 2022
1 parent 20d1e82 commit 3ca8545
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
10 changes: 7 additions & 3 deletions lib/proto.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,12 @@ def prototype
# traversed through instead.
def [](property)
property = property.to_s
property?(property) ? @table[property] : (@proto and @proto[property])
if property?(property)
@table[property]
else
return nil unless @proto
@proto.public_send(property)
end
end

##
Expand Down Expand Up @@ -133,9 +138,8 @@ def __add(property, value)

def __delete(property)
@table.delete(property)
@proto&.delete(property)
return unless instance_of?(method(property).owner)
define_singleton_method(property) { nil }
define_singleton_method(property) { self[property] }

This comment has been minimized.

Copy link
@awfulcooking

awfulcooking Mar 28, 2022

Perhaps this line can be omitted :)

rescue NameError
end
end
Expand Down
15 changes: 8 additions & 7 deletions spec/object_mixin_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,35 @@
let(:three) { object.create(two) }

context "when there is one prototype in the chain" do
context "when falling back to the property on the root prototype" do
context "when traversing to the property on the root prototype" do
subject { two.bar }
it { is_expected.to eq(42) }
end

context "when the property is deleted from the root prototype" do
before { two.delete("bar") }
before { one.delete("bar") }
subject { two.bar }
it { is_expected.to eq(nil) }
end
end

context "when there are two prototypes in the chain" do
context "when falling back to the property on the root prototype" do
context "when traversing to the property on the root prototype" do
subject { three.bar }
it { is_expected.to eq(42) }
end

context "when falling back to the property on the middle prototype" do
context "when traversing to the property on the middle prototype" do
let(:two) { object.create(one) { def bar = 84 } }
subject { three.bar }
it { is_expected.to eq(84) }
end

context "when the property is deleted from all prototypes in the chain" do
context "when the property is deleted from the middle prototype" do
let(:two) { object.create(one) { def bar = 84 } }
before { two.delete("bar") }
subject { two.bar }
it { is_expected.to eq(nil) }
subject { three.bar }
it { is_expected.to eq(42) }
end
end
end

1 comment on commit 3ca8545

@awfulcooking
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool

Please sign in to comment.