Class: RssNotifier::Adapter::Email

Inherits:
Object
  • Object
show all
Defined in:
lib/rss_notifier/adapter/email.rb

Constant Summary collapse

HTML_TEMPLATE =
File.expand_path('../email.html.erb', __FILE__)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(email, config) ⇒ Email

Returns a new instance of Email.

Parameters:



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rss_notifier/adapter/email.rb', line 15

def initialize(email, config)
  @config = config
  @email = email
  @template = ERB.new(File.read(HTML_TEMPLATE))

  @config[:adapters][:email][:from] or
    raise 'config[:adapters][:email][:from] is not configured.'

  @config[:adapters][:email][:sendgrid_api_key] or
    raise 'config[:adapters][:email][:sendgrid_api_key] is not configured.'
end

Instance Attribute Details

#emailObject (readonly)

Returns the value of attribute email.



9
10
11
# File 'lib/rss_notifier/adapter/email.rb', line 9

def email
  @email
end

Class Method Details

.client(api_key) ⇒ Object



65
66
67
68
# File 'lib/rss_notifier/adapter/email.rb', line 65

def self.client(api_key)
  @clients ||= {}
  @clients[api_key] ||= SendGrid::Client.new(api_key: api_key)
end

Instance Method Details

#notify(item) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rss_notifier/adapter/email.rb', line 27

def notify(item)
  b = binding
  b.local_variable_set(:item, item)
  html = @template.result(b)

  RssNotifier.logger.debug("Adapter::Email #{email}, #{html}")

  mail = SendGrid::Mail.new do |m|
    m.to = email
    m.from = @config[:adapters][:email][:from]
    m.subject = "#{item.feed.name} | #{item.title}"
    m.html = html
  end

  client = RssNotifier::Adapter::Email.client(@config[:adapters][:email][:sendgrid_api_key])

  begin
    res = client.send(mail)
    if res.code == 200
      RssNotifier.logger.debug("#{self} notified")
    else
      RssNotifier.logger.warn("Could not notify #{self}. Code=#{res.code}")
      p res.body
      return false
    end
  rescue => e
    puts e.to_s
    puts e.backtrace
    return false
  end

  true
end

#to_sObject



61
62
63
# File 'lib/rss_notifier/adapter/email.rb', line 61

def to_s
  "<Adapter::Email email=#{email}>"
end