Class: Tupper
- Inherits:
-
Object
- Object
- Tupper
- Defined in:
- lib/tupper.rb,
lib/tupper/version.rb
Constant Summary collapse
- DEFAULT_TMP_DIR =
File.join(%w{ / tmp tupper })
- SESSION_STORE_KEY =
'tupper_file_info'
- VERSION =
"1.0.0"
Instance Attribute Summary collapse
-
#file_info ⇒ Object
readonly
Returns the value of attribute file_info.
-
#temp_dir ⇒ Object
Returns the value of attribute temp_dir.
Instance Method Summary collapse
- #cleanup ⇒ Object
- #has_uploaded_file? ⇒ Boolean
-
#initialize(session) ⇒ Tupper
constructor
A new instance of Tupper.
- #original_file ⇒ Object
- #upload(file_info) ⇒ Object
- #uploaded_file ⇒ Object
Constructor Details
#initialize(session) ⇒ Tupper
Returns a new instance of Tupper.
11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/tupper.rb', line 11 def initialize session @session = session unless ((json = @session.fetch(SESSION_STORE_KEY, '')).empty?) begin @file_info = JSON.parse(json) rescue @session.delete(SESSION_STORE_KEY) raise RuntimeError.new('invalid session data') end end end |
Instance Attribute Details
#file_info ⇒ Object (readonly)
Returns the value of attribute file_info.
9 10 11 |
# File 'lib/tupper.rb', line 9 def file_info @file_info end |
#temp_dir ⇒ Object
Returns the value of attribute temp_dir.
9 10 11 |
# File 'lib/tupper.rb', line 9 def temp_dir @temp_dir end |
Instance Method Details
#cleanup ⇒ Object
55 56 57 58 59 |
# File 'lib/tupper.rb', line 55 def cleanup File.unlink uploaded_file if has_uploaded_file? @session.delete SESSION_STORE_KEY @file_info = nil end |
#has_uploaded_file? ⇒ Boolean
28 29 30 |
# File 'lib/tupper.rb', line 28 def has_uploaded_file? @file_info && File.exists?(@file_info.fetch("uploaded_file", '')) end |
#original_file ⇒ Object
51 52 53 |
# File 'lib/tupper.rb', line 51 def original_file (@file_info || {}).fetch('original_file', nil) end |
#upload(file_info) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/tupper.rb', line 32 def upload file_info unless @temp_dir self.temp_dir = DEFAULT_TMP_DIR end file_hash = "#{Time.now.to_i}_#{Digest::MD5.hexdigest(file_info[:filename]).slice(0, 8)}" uploaded_file = File.join(temp_dir, file_hash + File.extname(file_info[:filename])) FileUtils.copy(file_info[:tempfile], uploaded_file) tupper_file_info = { uploaded_file: uploaded_file, original_file: file_info[:filename], }.to_json @session.store SESSION_STORE_KEY, tupper_file_info end |
#uploaded_file ⇒ Object
47 48 49 |
# File 'lib/tupper.rb', line 47 def uploaded_file (@file_info || {}).fetch('uploaded_file', nil) end |