Skip to content
This repository has been archived by the owner on Jul 17, 2018. It is now read-only.

Commit

Permalink
Make SMTP connection lazy with a proxy
Browse files Browse the repository at this point in the history
Specs pending
  • Loading branch information
agorf committed Aug 12, 2017
1 parent df1807c commit dafad3a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 16 deletions.
37 changes: 21 additions & 16 deletions lib/feed2email/cli.rb
Expand Up @@ -148,19 +148,32 @@ def list
def process
require 'feed2email'
Feed2Email.setup_database(log: true)
Feed2Email.setup_mail_defaults
require 'feed2email/feed'

feeds = Feed.enabled.oldest_first

if config_data["send_method"] == "smtp"
with_smtp_connection do |smtp|
Feed2Email.smtp_connection = smtp
feeds.each(&:process)
Feed2Email.smtp_connection = nil
end
else
if config_data['send_method'] != 'smtp'
Feed2Email.setup_mail_defaults
feeds.each(&:process)
return
end

require 'feed2email/smtp_connection_proxy'

smtp = Net::SMTP.new(config_data['smtp_host'], config_data['smtp_port'])
smtp.enable_starttls if config_data['smtp_starttls']

Feed2Email.smtp_connection = SMTPConnectionProxy.new(smtp) do
smtp.start('localhost', config_data['smtp_user'],
config_data['smtp_pass'], config_data['smtp_auth'].to_sym)
end

Feed2Email.setup_mail_defaults

feeds.each(&:process)

if Feed2Email.smtp_connection.started?
Feed2Email.smtp_connection.finish
end
end

Expand Down Expand Up @@ -293,14 +306,6 @@ def interruptible
exit
end
end

# TODO make lazy with a wrapper
def with_smtp_connection(&block)
smtp = Net::SMTP.new(config_data["smtp_host"], config_data["smtp_port"])
smtp.enable_starttls if config_data["smtp_starttls"]
smtp.start("localhost", config_data["smtp_user"], config_data["smtp_pass"],
config_data["smtp_auth"].to_sym, &block)
end
end
end
end
19 changes: 19 additions & 0 deletions lib/feed2email/smtp_connection_proxy.rb
@@ -0,0 +1,19 @@
module Feed2Email
class SMTPConnectionProxy
attr_reader :smtp

def initialize(smtp, &start_smtp)
@smtp = smtp
@start_smtp = start_smtp
end

def method_missing(name, *args)
start_smtp.call(smtp) unless smtp.started?
smtp.public_send(name, *args) # delegate
end

private

attr_reader :start_smtp
end
end

0 comments on commit dafad3a

Please sign in to comment.