1 | require 'base64' |
||
2 | require 'mime' |
||
3 | require 'mime/types' |
||
4 | |||
5 | module MIMEBuilder |
||
6 | class Filepath |
||
7 | attr_accessor :mime |
||
8 | attr_accessor :filepath |
||
9 | |||
10 | def initialize(filepath, opts = {}) |
||
11 | if opts.key?(:base64_encode) && opts[:base64_encode] |
||
12 | @base64_encode = true |
||
13 | else |
||
14 | @base64_encode = false |
||
15 | end |
||
16 | |||
17 | @mime = create_mime(filepath, opts[:content_id_disable]) |
||
18 | |||
19 | @mime.headers.set( |
||
20 | 'Content-Type', |
||
21 | get_file_content_type(filepath, opts[:content_type])) |
||
22 | |||
23 | set_attachment_content_disposition(filepath, opts[:is_attachment]) |
||
24 | end |
||
25 | |||
26 | def create_mime(filepath, content_id_disable) |
||
27 | bytes = read_file_bytes(filepath) |
||
28 | |||
29 | mime = nil |
||
30 | |||
31 | if @base64_encode |
||
32 | mime = MIME::Text.new(Base64.encode64(bytes)) |
||
33 | mime.headers.set('Content-Transfer-Encoding', 'base64') |
||
34 | else |
||
35 | mime = MIME::Application.new(bytes) |
||
36 | end |
||
37 | |||
38 | mime.headers.delete('Content-Id') if content_id_disable |
||
39 | |||
40 | mime |
||
41 | end |
||
42 | |||
43 | def read_file_bytes(filepath = nil) |
||
44 | unless File.file?(filepath) |
||
45 | fail "File \"#{filepath}\" does not exist or cannot be read" |
||
46 | end |
||
47 | |||
48 | File.read(filepath) |
||
49 | end |
||
50 | |||
51 | def get_file_content_type(filepath = nil, content_type = nil) |
||
52 | if content_type.is_a?(String) && content_type =~ %r{^[^/\s]+/[^/\s]+} |
||
53 | return content_type |
||
54 | end |
||
55 | MIME::Types.type_for(filepath).first.content_type \ |
||
56 | || 'application/octet-stream' |
||
57 | end |
||
58 | |||
59 | def set_attachment_content_disposition(filepath, is_attachment) |
||
60 | @mime.headers.set( |
||
61 | 'Content-Disposition', |
||
62 | get_attachment_content_disposition(filepath) |
||
63 | ) if is_attachment |
||
64 | end |
||
65 | |||
66 | View Code Duplication | def get_attachment_content_disposition(filepath = nil) |
|
0 ignored issues
–
show
Duplication
introduced
by
![]() |
|||
67 | filename = File.basename(filepath.to_s) |
||
68 | if filename.to_s.length > 0 |
||
69 | return "attachment; filename=\"#{filename}\"" |
||
70 | end |
||
71 | 'attachment' |
||
72 | end |
||
73 | end |
||
74 | end |
||
75 |