BigW Consortium Gitlab

file_uploader.rb 1.04 KB
Newer Older
1
class FileUploader < CarrierWave::Uploader::Base
2
  include UploaderHelper
3
  MARKDOWN_PATTERN = %r{\!?\[.*?\]\(/uploads/(?<secret>[0-9a-f]{32})/(?<file>.*?)\)}
4

5 6
  storage :file

7 8
  attr_accessor :project, :secret

9
  def initialize(project, secret = nil)
Douwe Maan committed
10
    @project = project
11
    @secret = secret || self.class.generate_secret
12 13 14
  end

  def base_dir
15
    "uploads"
16 17 18
  end

  def store_dir
Douwe Maan committed
19
    File.join(base_dir, @project.path_with_namespace, @secret)
20 21 22
  end

  def cache_dir
Douwe Maan committed
23
    File.join(base_dir, 'tmp', @project.path_with_namespace, @secret)
24 25
  end

Douwe Maan committed
26
  def secure_url
27
    File.join("/uploads", @secret, file.filename)
Douwe Maan committed
28
  end
29

30 31 32 33
  def to_markdown
    to_h[:markdown]
  end

34
  def to_h
35
    filename = image_or_video? ? self.file.basename : self.file.filename
36 37 38
    escaped_filename = filename.gsub("]", "\\]")

    markdown = "[#{escaped_filename}](#{self.secure_url})"
39
    markdown.prepend("!") if image_or_video?
40 41 42 43 44 45 46

    {
      alt:      filename,
      url:      self.secure_url,
      markdown: markdown
    }
  end
47 48 49 50

  def self.generate_secret
    SecureRandom.hex
  end
51
end