Class: LogoSoup::Core::SvgDimensions

Inherits:
Object
  • Object
show all
Defined in:
lib/logosoup/core/svg_dimensions.rb

Overview

Extracts width/height from SVG XML.

Class Method Summary collapse

Class Method Details

.call(svg_string, on_error: nil) ⇒ Array(Float, Float)?

Parameters:

  • svg_string (String)
  • on_error (:raise, nil) (defaults to: nil)

Returns:

  • (Array(Float, Float), nil)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/logosoup/core/svg_dimensions.rb', line 12

def self.call(svg_string, on_error: nil)
  raw = svg_string.to_s
  return nil if raw.empty?

  doc = Nokogiri::XML(raw) { |cfg| cfg.nonet }
  svg = doc.at_xpath("//*[local-name()='svg']")
  return nil unless svg

  view_box = svg["viewBox"] || svg["viewbox"]
  if view_box
    parts = view_box.split(/[\s,]+/).filter_map do |p|
      Float(p)
    rescue ArgumentError, TypeError, RangeError => e
      handle_error(e, on_error: on_error)
      nil
    end
    return [parts[2], parts[3]] if parts.length == 4
  end

  w = numeric_dimension(svg["width"], on_error: on_error)
  h = numeric_dimension(svg["height"], on_error: on_error)
  return nil unless w && h

  [w, h]
end