BigW Consortium Gitlab

base.rb 2.46 KB
Newer Older
1 2
module BlobViewer
  class Base
3
    PARTIAL_PATH_PREFIX = 'projects/blob/viewers'.freeze
4

5
    class_attribute :partial_name, :loading_partial_name, :type, :extensions, :file_types, :load_async, :binary, :switcher_icon, :switcher_title, :collapse_limit, :size_limit
6 7 8

    self.loading_partial_name = 'loading'

9
    delegate :partial_path, :loading_partial_path, :rich?, :simple?, :load_async?, :text?, :binary?, to: :class
10 11 12

    attr_reader :blob

13 14
    delegate :project, to: :blob

15 16
    def initialize(blob)
      @blob = blob
17
      @initially_binary = blob.binary?
18 19 20
    end

    def self.partial_path
21 22 23 24 25
      File.join(PARTIAL_PATH_PREFIX, partial_name)
    end

    def self.loading_partial_path
      File.join(PARTIAL_PATH_PREFIX, loading_partial_name)
26 27 28 29 30 31 32 33 34 35
    end

    def self.rich?
      type == :rich
    end

    def self.simple?
      type == :simple
    end

36 37 38 39
    def self.auxiliary?
      type == :auxiliary
    end

40 41
    def self.load_async?
      load_async
42 43
    end

44 45
    def self.binary?
      binary
46 47
    end

48 49
    def self.text?
      !binary?
50 51
    end

52 53 54
    def self.can_render?(blob, verify_binary: true)
      return false if verify_binary && binary? != blob.binary?
      return true if extensions&.include?(blob.extension)
55
      return true if file_types&.include?(blob.file_type)
56 57

      false
58 59
    end

60 61
    def collapsed?
      return @collapsed if defined?(@collapsed)
62

63
      @collapsed = !blob.expanded? && collapse_limit && blob.raw_size > collapse_limit
64 65 66
    end

    def too_large?
67 68 69
      return @too_large if defined?(@too_large)

      @too_large = size_limit && blob.raw_size > size_limit
70 71
    end

72 73 74 75
    def binary_detected_after_load?
      !@initially_binary && blob.binary?
    end

76
    # This method is used on the server side to check whether we can attempt to
Douwe Maan committed
77
    # render the blob at all. Human-readable error messages are found in the
78 79 80 81 82 83 84
    # `BlobHelper#blob_render_error_reason` helper.
    #
    # This method does not and should not load the entire blob contents into
    # memory, and should not be overridden to do so in order to validate the
    # format of the blob.
    #
    # Prefer to implement a client-side viewer, where the JS component loads the
Douwe Maan committed
85
    # binary from `blob_raw_path` and does its own format validation and error
86
    # rendering, especially for potentially large binary formats.
87
    def render_error
88
      if too_large?
89
        :too_large
90 91
      elsif collapsed?
        :collapsed
92
      end
93 94 95
    end

    def prepare!
96
      # To be overridden by subclasses
97 98 99
    end
  end
end