Class: Explicit::Type::File

Inherits:
Explicit::Type show all
Includes:
ActionView::Helpers::NumberHelper
Defined in:
lib/explicit/type/file.rb

Constant Summary collapse

FILE_CLASSES =
[
  ActionDispatch::Http::UploadedFile,
  Rack::Test::UploadedFile
].freeze

Instance Attribute Summary collapse

Attributes inherited from Explicit::Type

#auth_type, #default, #description, #nilable, #param_location

Instance Method Summary collapse

Methods inherited from Explicit::Type

#auth_basic?, #auth_bearer?, build, #error_i18n, #mcp_schema, #merge_base_json_schema, #param_location_body?, #param_location_path?, #param_location_query?, #required?, #swagger_i18n, #swagger_schema

Constructor Details

#initialize(max_size: nil, content_types: nil) ⇒ File

Returns a new instance of File.



13
14
15
16
# File 'lib/explicit/type/file.rb', line 13

def initialize(max_size: nil, content_types: nil)
  @max_size = max_size
  @content_types = Array(content_types)
end

Instance Attribute Details

#content_typesObject (readonly)

Returns the value of attribute content_types.



6
7
8
# File 'lib/explicit/type/file.rb', line 6

def content_types
  @content_types
end

#max_sizeObject (readonly)

Returns the value of attribute max_size.



6
7
8
# File 'lib/explicit/type/file.rb', line 6

def max_size
  @max_size
end

Instance Method Details

#json_schema(flavour) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/explicit/type/file.rb', line 48

def json_schema(flavour)
  {
    type: "string",
    format: "binary",
    description_topics: [
      max_size&.then { swagger_i18n("file_max_size", max_size: number_to_human_size(_1)) },
      content_types.any? ? swagger_i18n("file_content_types", content_types: content_types.join(', ')) : nil
    ]
  }
end

#validate(value) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/explicit/type/file.rb', line 18

def validate(value)
  if !FILE_CLASSES.any? { |klass| value.is_a?(klass) }
    return error_i18n("file")
  end

  if max_size && value.size > max_size
    return error_i18n("file_max_size", max_size: number_to_human_size(max_size))
  end

  if content_types.any? && !content_types.include?(value.content_type)
    return error_i18n("file_content_type", allowed_content_types: content_types.inspect)
  end

  [:ok, value]
end