Class: MIMEBuilder::Filepath

Inherits:
Object
  • Object
show all
Defined in:
lib/mime_builder/file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filepath, opts = {}) ⇒ Filepath

Returns a new instance of Filepath.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/mime_builder/file.rb', line 10

def initialize(filepath, opts = {})
  if opts.key?(:base64_encode) && opts[:base64_encode]
    @base64_encode = true
  else
    @base64_encode = false
  end

  @mime = create_mime(filepath, opts[:content_id_disable])

  @mime.headers.set(
    'Content-Type',
    get_file_content_type(filepath, opts[:content_type]))

  set_attachment_content_disposition(filepath, opts[:is_attachment])
end

Instance Attribute Details

#filepathObject

Returns the value of attribute filepath.



8
9
10
# File 'lib/mime_builder/file.rb', line 8

def filepath
  @filepath
end

#mimeObject

Returns the value of attribute mime.



7
8
9
# File 'lib/mime_builder/file.rb', line 7

def mime
  @mime
end

Instance Method Details

#create_mime(filepath, content_id_disable) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/mime_builder/file.rb', line 26

def create_mime(filepath, content_id_disable)
  bytes = read_file_bytes(filepath)

  mime = nil

  if @base64_encode
    mime = MIME::Text.new(Base64.encode64(bytes))
    mime.headers.set('Content-Transfer-Encoding', 'base64')
  else
    mime = MIME::Application.new(bytes)
  end

  mime.headers.delete('Content-Id') if content_id_disable

  mime
end

#get_attachment_content_disposition(filepath = nil) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/mime_builder/file.rb', line 66

def get_attachment_content_disposition(filepath = nil)
  filename = File.basename(filepath.to_s)
  if filename.to_s.length > 0
    return "attachment; filename=\"#{filename}\""
  end
  'attachment'
end

#get_file_content_type(filepath = nil, content_type = nil) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/mime_builder/file.rb', line 51

def get_file_content_type(filepath = nil, content_type = nil)
  if content_type.is_a?(String) && content_type =~ %r{^[^/\s]+/[^/\s]+}
    return content_type
  end
  MIME::Types.type_for(filepath).first.content_type \
    || 'application/octet-stream'
end

#read_file_bytes(filepath = nil) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/mime_builder/file.rb', line 43

def read_file_bytes(filepath = nil)
  unless File.file?(filepath)
    fail "File \"#{filepath}\" does not exist or cannot be read"
  end

  File.read(filepath)
end

#set_attachment_content_disposition(filepath, is_attachment) ⇒ Object



59
60
61
62
63
64
# File 'lib/mime_builder/file.rb', line 59

def set_attachment_content_disposition(filepath, is_attachment)
  @mime.headers.set(
    'Content-Disposition',
    get_attachment_content_disposition(filepath)
  ) if is_attachment
end