Class: EmailTracker::Interceptor

Inherits:
Object
  • Object
show all
Defined in:
app/models/email_tracker/interceptor.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(message) ⇒ Interceptor

Returns a new instance of Interceptor.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'app/models/email_tracker/interceptor.rb', line 4

def initialize(message)
  @message = message
  @hashed_email_address = EmailTracker.hash_email_address(Array(message.to).first)
  @email = EmailTracker::Email.for_email(message.tracking_data)
  
  opts = Rails.application.config.action_mailer.default_url_options
  protocol = opts.fetch(:protocol, "https")
  host = opts.fetch(:host)
  @url_base = "#{protocol}://#{host}"
  
  if message.multipart?
    message.html_part.body = add_tracking(message.html_part.body)
  else
    message.body = add_tracking(message.body)
  end
  
  @email.sent!
end

Class Method Details

.delivering_email(message) ⇒ Object



51
52
53
# File 'app/models/email_tracker/interceptor.rb', line 51

def self.delivering_email(message)
  self.new(message)
end

Instance Method Details

#add_tracking(content) ⇒ Object



23
24
25
26
27
28
29
# File 'app/models/email_tracker/interceptor.rb', line 23

def add_tracking(content)
  begin
    add_tracking_links(add_tracking_image(content.to_s))
  rescue
    p $!
  end
end

#add_tracking_image(content) ⇒ Object



31
32
33
34
35
# File 'app/models/email_tracker/interceptor.rb', line 31

def add_tracking_image(content)
  tracking_url = "#{@url_base}/et/#{@email.id}/#{@hashed_email_address}.gif"
  tracking_html = "<img src=\"#{tracking_url}\" alt=\"\"/>"
  content.gsub("</body>", "#{tracking_html}</body>")
end


37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/models/email_tracker/interceptor.rb', line 37

def add_tracking_links(content)
  content.gsub!(/href\=['"]([^"']+)['"]/) do |match|
    url = $1
    if url.starts_with?("mailto")
      match
    else
      join_symbol = url.include?("?") ? "&" : "?"
      url = "href=\"" + (url.starts_with?("http") ? "" : @url_base) + "#{url}#{join_symbol}et=#{@email.id}_#{@hashed_email_address}\""
    end
  end
  
  content
end