Class: Source

Inherits:
Object
  • Object
show all
Defined in:
lib/source.rb

Constant Summary collapse

RANKS =
%w[svg webp apng png jpg jpeg jfif pjpeg pjp gif tif tiff bmp cur ico].freeze
RANKS_LENGTH =
RANKS.length

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Source

Returns a new instance of Source.

Raises:



5
6
7
8
9
10
11
12
13
14
# File 'lib/source.rb', line 5

def initialize(path)
  raise Jekyll::ImgError, "The 'src' parameter was not specified" if path.nil?
  raise Jekyll::ImgError, "The 'src' parameter was empty" if path.empty?

  path.strip!
  raise Jekyll::ImgError, "The 'src' parameter only contained whitespace" if path.empty?

  @path = path
  @absolute_path = @path.start_with?('/')
end

Instance Method Details

#generateObject

Array of source statements for filetypes that exist locally; return nil if @path points to a remote image

Returns:

  • array of source statements for filetypes that exist locally; return nil if @path points to a remote image



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/source.rb', line 18

def generate
  return nil if @path.nil? || @path.start_with?('http')

  result = sorted_files.map do |filename|
    mtype = mimetype filename
    next unless mtype

    <<~END_HTML
      <source srcset="#{filename}" type="#{mtype}">
    END_HTML
  end
  result&.compact&.map(&:strip)
end

#src_fallbackObject

Webp is the least desired variant, png is most desired variant.

Returns:

  • URL of external image, otherwise return specified path unless it is a webp; in which case return most desired image variant that exists.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/source.rb', line 35

def src_fallback
  return @path if @path.start_with? 'http'

  result = @absolute_path ? @path.delete_prefix('.') : @path
  png = result.gsub(/\.webp$/, '.png')
  return png if File.exist? png
  return result unless result.end_with? '.webp' # we know @path will be a webp after this

  files = sorted_files
  return files[0] if files.count == 1

  files.each do |filename|
    ext = File.extname filename
    unless ext == '.webp'
      return @absolute_path ? filename.delete_prefix('.') : filename
    end
  end
  result
end