Commit be432c3

mokha <mokha@cisco.com>
2019-02-27 18:25:34
add file publisher and command line option. tag: v0.1.0
1 parent d6a3678
Changed files (2)
lib/minbox/cli.rb
@@ -22,9 +22,10 @@ module Minbox
         end
       end
 
+      method_option :output, type: :array, default: ['stdout']
       desc 'server <HOST> <PORT>', 'SMTP server'
       def server(host = 'localhost', port = '25')
-        publisher = Publisher.new(LogPublisher.new, RedisPublisher.new)
+        publisher = publishers_for(options[:output])
         Server.new(host, port).listen! do |mail|
           publisher.publish(mail)
         end
@@ -34,6 +35,23 @@ module Minbox
       def version
         say Minbox::VERSION
       end
+
+      private
+
+      def publishers_for(output)
+        publisher = Publisher.new
+        output.each do |x|
+          case x
+          when 'stdout'
+            publisher.add(LogPublisher.new)
+          when 'redis'
+            publisher.add(RedisPublisher.new)
+          when 'file'
+            publisher.add(FilePublisher.new)
+          end
+        end
+        publisher
+      end
     end
   end
 end
lib/minbox/publisher.rb
@@ -8,6 +8,10 @@ module Minbox
       @publishers = Array(publishers)
     end
 
+    def add(publisher)
+      publishers.push(publisher)
+    end
+
     def publish(mail)
       publishers.each { |x| x.publish(mail) }
     end
@@ -32,4 +36,17 @@ module Minbox
       @redis.publish("minbox", mail.to_s)
     end
   end
+
+  class FilePublisher
+    attr_reader :dir
+
+    def initialize(dir = Dir.pwd)
+      @dir = File.join(dir, "tmp")
+      FileUtils.mkdir_p(@dir)
+    end
+
+    def publish(mail)
+      IO.write(File.join(dir, "#{Time.now.to_i}.eml"), mail.to_s)
+    end
+  end
 end