Class: UnitHelper

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

Overview

Simple class to provide a wrapper/common pattern around Ruby-Units

Class Method Summary collapse

Class Method Details

.abbreviation(unit) ⇒ Object

Unit is a RubyUnits::UnitDefinition



17
18
19
# File 'lib/unit_helper.rb', line 17

def abbreviation(unit)
  unit.aliases.first
end

.all_units(add_kind: false) ⇒ Object



42
43
44
45
46
# File 'lib/unit_helper.rb', line 42

def all_units(add_kind: false)
  Rails.cache.fetch([:units, :all, I18n.locale, :v9], expires_in: 1.week) do
    units_by_kind(:all, add_kind: add_kind)
  end
end

.display_name(unit) ⇒ Object

Unit is a RubyUnits::UnitDefinition



9
10
11
12
13
14
# File 'lib/unit_helper.rb', line 9

def display_name(unit)
  # the longest aliases seems the nicest compared to the display_name
  name_en = unit.aliases.max_by(&:length).titleize
  return name_en if I18n.locale.to_s.first(2) == 'en'
  TranslationKey.translate(name_en, I18n.locale, namespace: 'Units')
end

.kind_of_unitsObject



4
5
6
# File 'lib/unit_helper.rb', line 4

def kind_of_units
  RubyUnits::Unit.definitions.values.map(&:kind).uniq
end

.length_unitsObject



48
49
50
# File 'lib/unit_helper.rb', line 48

def length_units
  units_by_kind(:length)
end

.mass_unitsObject



52
53
54
# File 'lib/unit_helper.rb', line 52

def mass_units
  units_by_kind(:mass)
end

.unit_symbol(unit) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/unit_helper.rb', line 56

def unit_symbol(unit)
  case unit&.downcase
  when 'degf'
    " °F" # could be ℉ but seem too compressed
  when 'degc'
    " °C" # or ℃
  when 'ohm'
    " Ω"
  when "hertz"
    ""
  # when "kg"
  #   "㎏"
  when "ft"
    ""
  when "in"
    ""
  when "sqft"
    " ft²"
  when "sqin"
    " in²"
  when "m2"
    ""
  else
    " #{unit}"
  end
end

.units_by_kind(kind, add_kind: false) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/unit_helper.rb', line 21

def units_by_kind(kind, add_kind: false)
  udv = RubyUnits::Unit.definitions.values
  unless kind == :all || kind.nil?
    udv.select!{|d| d.kind.to_s == kind.to_s}
  end
  # Reject prefixes stuff
  udv.reject!{|d| d.kind == :prefix }
  udv.map do |ud|
    n = display_name(ud)
    v = abbreviation(ud)
    unless n.casecmp(v).zero?
      # We append the abbreviation in the name
      n = "#{n} (#{v})"
    end
    if add_kind
      n = "#{n} [#{ud.kind}]"
    end
    [n, v]
  end
end