Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorYorick Peterse <yorickpeterse@gmail.com>2016-05-26 14:13:57 +0300
committerYorick Peterse <yorickpeterse@gmail.com>2016-05-26 14:58:01 +0300
commit94d5416db6415b06706204fb4a4df0100bcab7be (patch)
tree566e4525629241e3182296afd12e4e92ebaa863f /lib/gitlab/lazy.rb
parent309ca405fa30e1eeaeaeddc0c8918e65c98ebbf7 (diff)
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.
Diffstat (limited to 'lib/gitlab/lazy.rb')
-rw-r--r--lib/gitlab/lazy.rb34
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/gitlab/lazy.rb b/lib/gitlab/lazy.rb
new file mode 100644
index 00000000000..2a659ae4c74
--- /dev/null
+++ b/lib/gitlab/lazy.rb
@@ -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