Commit 1f55ae3

mokha <mokha@cisco.com>
2019-04-16 16:54:31
extract methods for listening for filesystem changes
1 parent b60afc1
Changed files (2)
lib
minbox
spec
lib/minbox/inbox.rb
@@ -10,15 +10,8 @@ module Minbox
     end
 
     def initialize(root_dir:)
+      start_listening(root_dir)
       empty!
-      ::Listen.to(File.expand_path(root_dir), only: /\.eml$/) do |modified, added, removed|
-        added.each do |file|
-          @emails[File.basename(file)] = Mail.read(file)
-        end
-        removed.each do |file|
-          @emails.delete(File.basename(file))
-        end
-      end.start
     end
 
     def emails(count: 0)
@@ -58,5 +51,24 @@ module Minbox
         yield email
       end
     end
+
+    private
+
+    def changed(modified, added, removed)
+      added.each do |file|
+        @emails[File.basename(file)] = Mail.read(file)
+      end
+      removed.each do |file|
+        @emails.delete(File.basename(file))
+      end
+    end
+
+    def listener_for(dir)
+      ::Listen.to(File.expand_path(dir), only: /\.eml$/, &method(:changed))
+    end
+
+    def start_listening(root_dir)
+      listener_for(root_dir).start
+    end
   end
 end
spec/minbox/inbox_spec.rb
@@ -57,6 +57,8 @@ RSpec.describe Minbox::Inbox do
     context "when opening an email by subject" do
       specify { expect(subject.open(subject: 'goodbye world').subject).to eql('goodbye world') }
       specify { expect(subject.open(subject: /goodbye/).subject).to eql('goodbye world') }
+      specify { expect(subject.open(subject: /hello/).subject).to eql('hello world') }
+      specify { expect(subject.open(subject: /world/).subject).to eql('hello world') }
     end
 
     context "when opening an email not in the inbox" do