image_service.rb 1006 Bytes
Newer Older
Marin Jankovski's avatar
Marin Jankovski committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module Projects
  class ImageService < BaseService
    include Rails.application.routes.url_helpers
    def initialize(repository, params, root_url)
      @repository, @params, @root_url = repository, params.dup, root_url
    end

    def execute
      uploader = FileUploader.new('uploads', upload_path, accepted_images)
      image = @params['markdown_img']

      if image && correct_mime_type?(image)
        alt = image.original_filename
        uploader.store!(image)
        link = {
                 'alt' => File.basename(alt, '.*'),
17
                 'url' => File.join(@root_url, uploader.url)
Marin Jankovski's avatar
Marin Jankovski committed
18
19
20
21
22
23
               }
      else
        link = nil
      end
    end

24
    protected
Marin Jankovski's avatar
Marin Jankovski committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

    def upload_path
      base_dir = FileUploader.generate_dir
      File.join(@repository.path_with_namespace, base_dir)
    end

    def accepted_images
      %w(png jpg jpeg gif)
    end

    def correct_mime_type?(image)
      accepted_images.map{ |format| image.content_type.include? format }.any?
    end
  end
end