Module: Odin::Forms::Units

Defined in:
lib/odin/forms/units.rb

Overview

Measurement-unit conversion between page units and CSS pixels.

Constant Summary collapse

DPI =
96.0
CONVERSIONS =
{
  "inch" => DPI,
  "cm" => DPI / 2.54,
  "mm" => DPI / 25.4,
  "pt" => DPI / 72.0,
}.freeze

Class Method Summary collapse

Class Method Details

.from_pixels(px, unit) ⇒ Object

Convert pixels back to the given unit, rounded to 3 decimals.

Raises:

  • (ArgumentError)


27
28
29
30
31
32
# File 'lib/odin/forms/units.rb', line 27

def from_pixels(px, unit)
  factor = CONVERSIONS[unit.to_s]
  raise ArgumentError, "Unknown unit: #{unit}" unless factor

  round3(px / factor)
end

.round3(n) ⇒ Object

Round to 3 decimal places, returning an integer when whole.



35
36
37
38
# File 'lib/odin/forms/units.rb', line 35

def round3(n)
  r = (n * 1000).round / 1000.0
  r == r.to_i ? r.to_i : r
end

.to_pixels(value, unit) ⇒ Object

Convert a value in the given unit to pixels, rounded to 3 decimals.

Raises:

  • (ArgumentError)


19
20
21
22
23
24
# File 'lib/odin/forms/units.rb', line 19

def to_pixels(value, unit)
  factor = CONVERSIONS[unit.to_s]
  raise ArgumentError, "Unknown unit: #{unit}" unless factor

  round3(value * factor)
end