lib/ruby_units/ruby-units.rb in ruby-units-1.1.4 vs lib/ruby_units/ruby-units.rb in ruby-units-1.1.5
- old
+ new
@@ -38,11 +38,11 @@
# }
# end
# Unit.setup
class Unit < Numeric
# pre-generate hashes from unit definitions for performance.
- VERSION = '1.1.4'
+ VERSION = '1.1.5'
@@USER_DEFINITIONS = {}
@@PREFIX_VALUES = {}
@@PREFIX_MAP = {}
@@UNIT_MAP = {}
@@UNIT_VALUES = {}
@@ -130,12 +130,12 @@
@@UNIT_MAP[name]=key
end
end
@@OUTPUT_MAP[key]=value[0][0]
end
- @@PREFIX_REGEX = @@PREFIX_MAP.keys.sort_by {|prefix| prefix.length}.reverse.join('|')
- @@UNIT_REGEX = @@UNIT_MAP.keys.sort_by {|unit| unit.length}.reverse.join('|')
+ @@PREFIX_REGEX = @@PREFIX_MAP.keys.sort_by {|prefix| [prefix.length, prefix]}.reverse.join('|')
+ @@UNIT_REGEX = @@UNIT_MAP.keys.sort_by {|unit| [unit.length, unit]}.reverse.join('|')
@@UNIT_MATCH_REGEX = /(#{@@PREFIX_REGEX})*?(#{@@UNIT_REGEX})\b/
Unit.new(1)
end
@@ -370,15 +370,15 @@
self.to($2).to_s($1)
else
"#{$1 % @scalar} #{$2 || self.units}".strip
end
rescue
- (Time.gm(0) + self).strftime(target_units)
+ (DateTime.new(0) + self).strftime(target_units)
end
- when /(\S+)/ #unit only 'mm' or '1/mm'
+ when /(\S+)/ #unit only 'mm' or '1/mm'
"#{self.to($1).to_s}"
- else #strftotime?
+ else
raise "unhandled case"
end
else
out = case @scalar
when Rational :
@@ -1042,11 +1042,11 @@
copy(unit)
@scalar *= mult
@base_scalar *= mult
return self
end
-
+ unit_string.gsub!(/<(#{@@UNIT_REGEX})><(#{@@UNIT_REGEX})>/, '\1*\2')
unit_string.gsub!(/[<>]/,"")
if unit_string =~ /:/
hours, minutes, seconds, microseconds = unit_string.scan(TIME_REGEX)[0]
raise ArgumentError, "Invalid Duration" if [hours, minutes, seconds, microseconds].all? {|x| x.nil?}
@@ -1077,11 +1077,10 @@
end
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.count('/') > 1
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.scan(/\s[02-9]/).size > 0
@scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] #parse the string into parts
-
top.scan(TOP_REGEX).each do |item|
n = item[1].to_i
x = "#{item[0]} "
case
when n>=0 : top.gsub!(/#{item[0]}(\^|\*\*)#{n}/) {|s| x * n}
@@ -1094,11 +1093,13 @@
@numerator ||= UNITY_ARRAY
@denominator ||= UNITY_ARRAY
@numerator = top.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if top
@denominator = bottom.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if bottom
+
+
us = "#{(top || '' + bottom || '')}".to_s.gsub(@@UNIT_MATCH_REGEX,'').gsub(/[\d\*, "'_^\/\$]/,'')
- raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") unless us.empty?
+ raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized #{us.inspect}") unless us.empty?
@numerator = @numerator.map do |item|
@@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]
end.flatten.compact.delete_if {|x| x.empty?}