Skip to content

Commit

Permalink
Merge branch 'vlad-pisanov-vp_fix_falsy_memoization'
Browse files Browse the repository at this point in the history
Version 0.2.0
  • Loading branch information
albertosaurus committed Aug 29, 2023
2 parents 0faf4b3 + cbde390 commit 8365a96
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/lazy_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# lazy.get_expensive_results(foo, bar) # Initializes VeryExpensiveObject and calls 'get_expensive_results' on it, passing in foo and bar
class LazyObject < BasicObject
def self.version
'0.1.0'
'0.2.0'
end

def initialize(&callable)
Expand All @@ -31,7 +31,11 @@ def !

# Cached target object.
def __target_object__
@__target_object__ ||= @__callable__.call
if defined?(@__target_object__)
@__target_object__
else
@__target_object__ = @__callable__.call
end
end

# Forwards all method calls to the target object.
Expand Down
18 changes: 18 additions & 0 deletions spec/lazy_object_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,24 @@ def method_with_kwargs_and_yield(**kwargs)
end
end

context "when target object evaluates to a falsy value" do
let(:lazy_object) { LazyObject.new { TargetObject.new } }

it "evaluates the block exactly once for false" do
TargetObject.should_receive(:new).once.and_return(false)
3.times do
expect(lazy_object).to eq(false)
end
end

it "evaluates the block exactly once for nil" do
TargetObject.should_receive(:new).once.and_return(nil)
3.times do
expect(lazy_object).to eq(nil)
end
end
end

context "equality operators" do
it "should return correct value when comparing" do
one = LazyObject.new { 1 }
Expand Down

0 comments on commit 8365a96

Please sign in to comment.