Module: Tins::Unit
- Defined in:
- lib/tins/unit.rb
Defined Under Namespace
Classes: FormatParser, ParserError, Prefix, UnitParser
Constant Summary
collapse
- PREFIX_LC =
[
'', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y',
].each_with_index.map { |n, i| Prefix.new(n.freeze, 1000, 1000 ** i, false) }.freeze
- PREFIX_UC =
[
'', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y',
].each_with_index.map { |n, i| Prefix.new(n.freeze, 1024, 1024 ** i, false) }.freeze
- PREFIX_F =
[
'', 'm', 'ยต', 'n', 'p', 'f', 'a', 'z', 'y',
].each_with_index.map { |n, i| Prefix.new(n.freeze, 1000, 1000 ** -i, true) }.freeze
Class Method Summary
collapse
Class Method Details
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/tins/unit.rb', line 36
def format(value, format: '%f %U', prefix: 1024, unit: ?b)
prefixes = prefixes(prefix)
first_prefix = prefixes.first or
raise ArgumentError, 'a non-empty array of prefixes is required'
if value.zero?
result = format.sub('%U', unit)
result %= value
else
prefix = prefixes[
(first_prefix.fraction ? -1 : 1) * Math.log(value.abs) / Math.log(first_prefix.step)
]
result = format.sub('%U', "#{prefix.name}#{unit}")
result %= (value / prefix.multiplier.to_f)
end
end
|
.parse(string, format: '%f %U', unit: ?b, prefix: nil) ⇒ Object
Parse the string string
if it matches format
with the unit unit
and the prefixes specified by prefix
.
169
170
171
172
|
# File 'lib/tins/unit.rb', line 169
def parse(string, format: '%f %U', unit: ?b, prefix: nil)
prefixes = prefixes(prefix)
FormatParser.new(format, UnitParser.new(string, unit, prefixes)).parse
end
|
.parse?(string, **options) ⇒ Boolean
174
175
176
177
178
|
# File 'lib/tins/unit.rb', line 174
def parse?(string, **options)
parse(string, **options)
rescue ParserError
nil
end
|
.prefixes(identifier) ⇒ Object
23
24
25
26
27
28
29
30
31
32
33
34
|
# File 'lib/tins/unit.rb', line 23
def prefixes(identifier)
case identifier
when :uppercase, :uc, 1024
PREFIX_UC
when :lowercase, :lc, 1000
PREFIX_LC
when :fraction, :f, 0.001
PREFIX_F
when Array
identifier
end
end
|