-
Notifications
You must be signed in to change notification settings - Fork 13
/
agreement_letter.rb
106 lines (96 loc) · 2.88 KB
/
agreement_letter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# == Schema Information
#
# Table name: agreement_letters
#
# id :integer not null, primary key
# user_id :integer not null
# event_id :integer not null
# path :string not null
# created_at :datetime not null
# updated_at :datetime not null
#
class AgreementLetter < ActiveRecord::Base
belongs_to :user
belongs_to :event
validates :user, :event, :path, presence: true
MAX_SIZE = 300_000_000
ALLOWED_MIMETYPE = "application/pdf"
STORAGE_DIR = Rails.root.join('storage', 'agreement_letters')
# Generates a unique filename for an AgreementLetter's file
#
# @raise [ArgumentError] if user or event are nil
# @param none
# @return [String] for the AgreementLetter's file name
def filename
event.nil? ? nil : "#{event.id}_#{user.id}.pdf"
end
# Saves a file in the AgreementLetter's path
#
# @param [ActionDispatch::Http::UploadedFile] the file to save
# @return [Boolean] whether saving the file was saved
def save_file(file)
unless valid_file?(file)
self.destroy
return false
end
begin
File.write(path, file.read, mode: 'wb')
true
rescue IOError
self.destroy
errors.add(I18n.t('agreement_letters.file_error'), I18n.t('agreement_letters.write_failed'))
false
end
end
# Calls super, adds an error if save fails
def save(*args)
if super
true
else
errors.add(I18n.t('agreement_letters.file_error'), I18n.t('agreement_letters.upload_failed'))
false
end
end
# Sets the AgreementLetter's path field to the path where the file should be saved
#
# @param none
# @return [String] the set path
def set_path
self.path = File.join(STORAGE_DIR, filename).to_s unless filename.nil?
end
private
def valid_file?(file)
if !is_file?(file)
errors.add(I18n.t('agreement_letters.file_error'), I18n.t("agreement_letters.not_a_file"))
false
elsif too_big?(file)
errors.add(I18n.t('agreement_letters.file_error'), I18n.t("agreement_letters.file_too_big"))
false
elsif wrong_filetype?(file)
errors.add(I18n.t('agreement_letters.file_error'), I18n.t("agreement_letters.wrong_filetype"))
false
elsif unable_to_open?(file)
errors.add(I18n.t('agreement_letters.file_error'), I18n.t("agreement_letters.corrupt_document"))
false
else
true
end
end
def is_file?(file)
file.respond_to?(:open) && file.respond_to?(:content_type) && file.respond_to?(:size)
end
def too_big?(file)
file.size > MAX_SIZE
end
def wrong_filetype?(file)
file.content_type != ALLOWED_MIMETYPE
end
def unable_to_open? file
begin
PDF::Inspector::Page.analyze_file(file.open)
false
rescue PDF::Reader::UnsupportedFeatureError, PDF::Reader::MalformedPDFError
true
end
end
end