Module: Emjay::WidthParser

Defined in:
lib/emjay/helpers/width_parser.rb

Constant Summary collapse

UNIT_REGEX =
/[\d.,]*(\D*)$/

Class Method Summary collapse

Class Method Details

.call(width, parse_float_to_int: true) ⇒ Object

Parses a width string like “600px” or “50%” into { parsed_width:, unit: }. Port of widthParser.js



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/emjay/helpers/width_parser.rb', line 9

def self.call(width, parse_float_to_int: true)
  width_str = width.to_s
  unit_match = UNIT_REGEX.match(width_str)
  width_unit = unit_match ? unit_match[1] : ""

  parsed_width = if width_unit == "%" && !parse_float_to_int
    width_str.to_f
  else
    width_str.to_i
  end

  {
    parsed_width: parsed_width,
    unit: width_unit.empty? ? "px" : width_unit
  }
end