Commit bbff9ef

mo khan <mo@mokhan.ca>
2014-07-25 22:39:11
extract storage class.
1 parent eef9f2a
lib/tfa/add_command.rb
@@ -1,15 +1,13 @@
 module TFA
   class AddCommand
     def initialize(storage)
-      @storage = storage
+      @storage = Storage.new(storage)
     end
 
     def run(arguments)
       name = arguments.first
       secret = arguments.last
-      @storage.transaction do
-        @storage[name] = secret
-      end
+      @storage.save(name, secret)
       "Added #{name}"
     end
   end
lib/tfa/show_command.rb
@@ -1,21 +1,45 @@
 module TFA
   class ShowCommand
     def initialize(storage)
-      @storage = storage
+      @storage = Storage.new(storage)
     end
 
     def run(arguments)
-      if arguments.any?
-        name = arguments.last
-        @storage.transaction(true) do
-          @storage[name]
-        end
-      else
-        @storage.transaction(true) do
-          @storage.roots.map do |key|
-            @storage[key]
-          end
-        end
+      return @storage.secret_for(arguments.last) if arguments.any?
+      @storage.all_secrets
+    end
+  end
+end
+
+module TFA
+  class Storage
+    def initialize(storage)
+      @storage = storage
+    end
+
+    def all_secrets
+      open_readonly do |storage|
+        storage.roots.map { |key| { key => storage[key] } }
+      end
+    end
+
+    def secret_for(key)
+      open_readonly do |storage|
+        storage[key]
+      end
+    end
+
+    def save(key, value)
+      @storage.transaction do
+        @storage[key] = value
+      end
+    end
+
+    private
+
+    def open_readonly
+      @storage.transaction(true) do
+        yield @storage
       end
     end
   end
spec/lib/show_command_spec.rb
@@ -24,7 +24,7 @@ module TFA
             storage['production'] = "3"
           end
 
-          expect(subject.run([])).to eql(["1", "2", "3"])
+          expect(subject.run([])).to eql([{"development" => "1"}, { "staging" => "2" }, { "production" => "3" }])
         end
       end
     end