Commit 6d6bb89

mo khan <mo@mokhan.ca>
2013-12-27 17:50:32
create lazy loader.
1 parent 34b873d
Changed files (3)
lib/nasty/lazy.rb
@@ -0,0 +1,23 @@
+module Nasty
+  class Lazy 
+    def initialize(factory = ->(key) { key.new }, *arguments)
+      @factory = factory
+      @arguments = arguments
+    end
+
+    def method_missing(name, *args, &block)
+      @target ||= @factory.call(*@arguments)
+      @target.send(name, args, &block)
+    end
+
+    class << self
+      def bind_resolver(&block)
+        @@factory = block
+      end
+
+      def load(key, factory = @@factory)
+        Lazy.new(factory, key)
+      end
+    end
+  end
+end
lib/nasty.rb
@@ -5,6 +5,7 @@ require "nasty/composite_command"
 require "nasty/expose_binding"
 require "nasty/kernel"
 require "nasty/lambda_behaviours"
+require "nasty/lazy"
 require "nasty/log"
 require "nasty/object"
 require "nasty/version"
spec/unit/lazy_spec.rb
@@ -0,0 +1,35 @@
+require "spec_helper"
+
+module Nasty
+  describe Lazy do
+    context "when lazy loading an item from a factory" do
+      context "when invoking a method on the proxy" do
+        let(:factory) { double }
+        let(:blackbook) { double }
+
+        before :each do
+          blackbook.stub(:find).and_return("nasty")
+          Lazy.bind_factory do |key|
+            blackbook if key == :blackbook
+          end
+        end
+
+        it "should invoke the target" do
+          Lazy.load(:blackbook).find(:booty).should == "nasty"
+        end
+      end
+
+      context "before invocation" do
+        let(:factory) { ->(*args) { @called = true } }
+
+        before :each do
+          Lazy.load(:blackbook, factory)
+        end
+
+        it "does not resolve the component from the factory" do
+          @called.should be_false
+        end
+      end
+    end
+  end
+end