Class: DynamicImage::Breakpoints

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

Overview

DynamicImage Breakpoints

Computes the candidate widths for a srcset, given the widest the image can be rendered at.

A range steps down geometrically from the available width, an array lists the widths outright, and a single number gives one candidate.

Examples:

DynamicImage::Breakpoints.new(320..3200).widths(2000)
# => [370, 520, 720, 1020, 1420, 2000]

DynamicImage::Breakpoints.new([400, 800, 1600]).widths(1000)
# => [400, 800]

See Also:

Constant Summary collapse

SNAP =

Candidate widths are snapped down to a multiple of this, so that images of similar size share widths.

10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(spec = nil, step: nil) ⇒ Breakpoints

Returns a new instance of Breakpoints.

Parameters:

Raises:

  • (ArgumentError)

    if the step or range would never terminate



34
35
36
37
38
# File 'lib/dynamic_image/breakpoints.rb', line 34

def initialize(spec = nil, step: nil)
  @spec = spec.nil? ? DynamicImage.default_breakpoints : spec
  @step = (step || DynamicImage.breakpoint_step).to_f
  validate!
end

Instance Attribute Details

#specRange, ... (readonly)

Returns:

  • (Range, Array<Integer>, Integer)


27
28
29
# File 'lib/dynamic_image/breakpoints.rb', line 27

def spec
  @spec
end

#stepObject (readonly)

Returns the value of attribute step.



27
# File 'lib/dynamic_image/breakpoints.rb', line 27

attr_reader :spec, :step

Instance Method Details

#widths(available) ⇒ Array<Integer>

Returns the candidate widths, smallest first.

The largest candidate is always the available width, whether or not it falls inside the range. An image narrower than the range gets a single candidate.

Parameters:

Returns:

  • (Array<Integer>)

Raises:

  • (ArgumentError)

    if the spec isn't understood



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/dynamic_image/breakpoints.rb', line 49

def widths(available)
  available = available.to_i
  return [] unless available.positive?

  case spec
  when Range then stepped(available)
  when Array then fixed(available)
  when Integer then [spec]
  else unknown_spec!
  end
end