Module: Bible270::Avatars

Defined in:
lib/bible270/avatars.rb

Overview

What counts as an acceptable avatar. Kept free of Rails and of Active Storage so the rules can be unit tested, and so the engine still loads in an app that has Active Storage disabled.

Constant Summary collapse

CONTENT_TYPES =
%w[image/png image/jpeg image/gif image/webp].freeze
DEFAULT_MAX_BYTES =

Two megabytes. Large enough for a photo off a phone, small enough that nobody's profile page crawls.

2 * 1024 * 1024

Class Method Summary collapse

Class Method Details

.acceptable_size?(byte_size) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
# File 'lib/bible270/avatars.rb', line 27

def acceptable_size?(byte_size)
  size = byte_size.to_i
  size.positive? && size <= max_bytes
end

.acceptable_type?(content_type) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/bible270/avatars.rb', line 23

def acceptable_type?(content_type)
  CONTENT_TYPES.include?(content_type.to_s.downcase.split(';').first.to_s.strip)
end

.content_typesObject



16
# File 'lib/bible270/avatars.rb', line 16

def content_types = CONTENT_TYPES

.human_size(bytes) ⇒ Object



41
42
43
44
# File 'lib/bible270/avatars.rb', line 41

def human_size(bytes)
  mb = bytes.to_f / (1024 * 1024)
  mb >= 1 ? "#{format('%g', mb.round(1))}MB" : "#{(bytes.to_f / 1024).round}KB"
end

.max_bytesObject



18
19
20
21
# File 'lib/bible270/avatars.rb', line 18

def max_bytes
  configured = Bible270.config.avatar_max_bytes if Bible270.config.respond_to?(:avatar_max_bytes)
  configured.to_i.positive? ? configured.to_i : DEFAULT_MAX_BYTES
end

.problem_with(content_type:, byte_size:) ⇒ Object

nil when the upload is fine, otherwise the reason — phrased for a reader.



33
34
35
36
37
38
39
# File 'lib/bible270/avatars.rb', line 33

def problem_with(content_type:, byte_size:)
  return 'must be a PNG, JPEG, GIF or WebP image' unless acceptable_type?(content_type)
  return 'looks empty' unless byte_size.to_i.positive?
  return "must be under #{human_size(max_bytes)}" unless acceptable_size?(byte_size)

  nil
end