Files
Notare/lib/notare/width_parser.rb
mathias234 843466549a
All checks were successful
CI Pipeline / build (pull_request) Successful in 13s
Support table and table column sizing
2025-12-03 13:50:56 +01:00

32 lines
999 B
Ruby

# frozen_string_literal: true
module Notare
module WidthParser
TWIPS_PER_INCH = 1440
TWIPS_PER_CM = 567
PCT_MULTIPLIER = 50
ParsedWidth = Struct.new(:value, :type, keyword_init: true)
def self.parse(value)
case value
when :auto, nil
ParsedWidth.new(value: 0, type: "auto")
when Integer
ParsedWidth.new(value: value, type: "dxa")
when /\A(\d+(?:\.\d+)?)\s*in\z/i
twips = (::Regexp.last_match(1).to_f * TWIPS_PER_INCH).to_i
ParsedWidth.new(value: twips, type: "dxa")
when /\A(\d+(?:\.\d+)?)\s*cm\z/i
twips = (::Regexp.last_match(1).to_f * TWIPS_PER_CM).to_i
ParsedWidth.new(value: twips, type: "dxa")
when /\A(\d+(?:\.\d+)?)\s*%\z/
pct = (::Regexp.last_match(1).to_f * PCT_MULTIPLIER).to_i
ParsedWidth.new(value: pct, type: "pct")
else
raise ArgumentError, "Invalid width: #{value}. Use '2in', '5cm', '50%', :auto, or integer twips."
end
end
end
end