Added Gitlab::Lazy

This class can be used to lazy-evaluate blocks of code the first time
they're called. This can be useful when a method performs a certain
heavy operation (e.g. a SQL query) that you only want to perform
whenever the result is used for the first time.
This commit is contained in:
Yorick Peterse 2016-05-26 13:13:57 +02:00
parent 309ca405fa
commit 94d5416db6
No known key found for this signature in database
GPG key ID: EDD30D2BEB691AC9
2 changed files with 71 additions and 0 deletions

34
lib/gitlab/lazy.rb Normal file
View file

@ -0,0 +1,34 @@
module Gitlab
# A class that can be wrapped around an expensive method call so it's only
# executed when actually needed.
#
# Usage:
#
# object = Gitlab::Lazy.new { some_expensive_work_here }
#
# object['foo']
# object.bar
class Lazy < BasicObject
def initialize(&block)
@block = block
end
def method_missing(name, *args, &block)
__evaluate__
@result.__send__(name, *args, &block)
end
def respond_to_missing?(name, include_private = false)
__evaluate__
@result.respond_to?(name, include_private) || super
end
private
def __evaluate__
@result = @block.call unless defined?(@result)
end
end
end

View file

@ -0,0 +1,37 @@
require 'spec_helper'
describe Gitlab::Lazy, lib: true do
let(:dummy) { double(:dummy) }
context 'when not calling any methods' do
it 'does not call the supplied block' do
expect(dummy).not_to receive(:foo)
described_class.new { dummy.foo }
end
end
context 'when calling a method on the object' do
it 'lazy loads the value returned by the block' do
expect(dummy).to receive(:foo).and_return('foo')
lazy = described_class.new { dummy.foo }
expect(lazy.to_s).to eq('foo')
end
end
describe '#respond_to?' do
it 'returns true for a method defined on the wrapped object' do
lazy = described_class.new { 'foo' }
expect(lazy).to respond_to(:downcase)
end
it 'returns false for a method not defined on the wrapped object' do
lazy = described_class.new { 'foo' }
expect(lazy).not_to respond_to(:quack)
end
end
end