BigW Consortium Gitlab

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

6 7
  storage :file

8 9
  attr_accessor :project, :secret

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

  def base_dir
16
    "uploads"
17 18 19
  end

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

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

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

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

35 36 37 38 39 40 41 42 43 44 45 46 47 48
  def to_h
    filename = image? ? self.file.basename : self.file.filename
    escaped_filename = filename.gsub("]", "\\]")

    markdown = "[#{escaped_filename}](#{self.secure_url})"
    markdown.prepend("!") if image?

    {
      alt:      filename,
      url:      self.secure_url,
      is_image: image?,
      markdown: markdown
    }
  end
49 50 51 52

  def self.generate_secret
    SecureRandom.hex
  end
53
end