Class: FileAttachment

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/file_attachment.rb

Overview

t.string “name” t.text “description” t.string “filepath” t.integer “event_id” t.datetime “created_at” t.datetime “updated_at”

Constant Summary collapse

REL_ROOT_DIR =
File.join 'public', 'files'
ABS_ROOT_DIR =
File.join Rails.root, REL_ROOT_DIR

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#uploaded_fileObject

Returns the value of attribute uploaded_file.



29
30
31
# File 'app/models/file_attachment.rb', line 29

def uploaded_file
  @uploaded_file
end

Instance Method Details

#file_containerObject



108
109
110
111
# File 'app/models/file_attachment.rb', line 108

def file_container
  return nil unless attachable_type.present? && attachable_id.present?
  "#{attachable_type}_#{attachable_id}"
end

#file_container=(container) ⇒ Object



112
113
114
115
116
# File 'app/models/file_attachment.rb', line 112

def file_container=(container)
  p = container.split("_")
  self.attachable_type = p[0].blank? ? nil : p[0]
  self.attachable_id = p[1].blank? ? nil : p[1]
end

#file_saved?Boolean

Returns:

  • (Boolean)


104
105
106
107
# File 'app/models/file_attachment.rb', line 104

def file_saved?
  return true if File.exists?(full_path) && File.basename(full_path) != REL_ROOT_DIR.split("/").last
  return false
end

#full_pathObject



95
96
97
98
99
100
101
102
103
# File 'app/models/file_attachment.rb', line 95

def full_path
  # for backward compat; previous releases stored filepath relative to 'public'.
  # ie 'public' was not included in the filepath
  if filepath.include? REL_ROOT_DIR
    File.join Rails.root, filepath
  else
    File.join Rails.root, 'public', filepath
  end
end

#update_filepathObject

update fs & db filepaths with updated values (eg after dev changes)



119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'app/models/file_attachment.rb', line 119

def update_filepath
  old_path = full_path.dup
  build_filepath
  FileUtils.mv(old_path, full_path)
  unless file_saved?
    msg = "Error updating filepath for #{name}"
    logger.error(msg)
    errors.add(:base, msg)
    false
  else
    self.save
  end
end