Module: Postscale::Attachments

Defined in:
lib/postscale/attachments.rb

Constant Summary collapse

MAX_ATTACHMENTS_PER_EMAIL =
10
MAX_ATTACHMENT_BYTES =
25 * 1024 * 1024
MAX_TOTAL_ATTACHMENT_BYTES =
50 * 1024 * 1024

Class Method Summary collapse

Class Method Details

.from_bytes(filename, data, content_type = "application/octet-stream") ⇒ Object



15
16
17
18
19
20
21
# File 'lib/postscale/attachments.rb', line 15

def from_bytes(filename, data, content_type = "application/octet-stream")
  {
    "filename" => filename,
    "content" => Base64.strict_encode64(data.to_s),
    "content_type" => content_type
  }
end

.from_file(path, content_type = "application/octet-stream") ⇒ Object



11
12
13
# File 'lib/postscale/attachments.rb', line 11

def from_file(path, content_type = "application/octet-stream")
  from_bytes(File.basename(path), File.binread(path), content_type)
end

.validate(attachments) ⇒ Object

Raises:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/postscale/attachments.rb', line 23

def validate(attachments)
  return if attachments.nil? || attachments.empty?

  unless attachments.is_a?(Array)
    raise ValidationError, "attachments must be an array."
  end

  if attachments.length > MAX_ATTACHMENTS_PER_EMAIL
    raise ValidationError, "Postscale supports at most #{MAX_ATTACHMENTS_PER_EMAIL} attachments per email."
  end

  total = 0
  attachments.each_with_index do |attachment, index|
    filename = value_for(attachment, "filename")
    content = value_for(attachment, "content")

    raise ValidationError, "attachments[#{index}].filename is required." if blank?(filename)
    raise ValidationError, "attachments[#{index}].content is required." if blank?(content)

    bytes = decoded_bytes(content, index)
    if bytes > MAX_ATTACHMENT_BYTES
      raise ValidationError, "attachments[#{index}] exceeds the 25 MB per-attachment limit."
    end
    total += bytes
  end

  raise ValidationError, "Attachments exceed the 50 MB total message limit." if total > MAX_TOTAL_ATTACHMENT_BYTES
end