Unit name normalization

This commit is contained in:
Dan Elbert 2016-01-15 09:41:24 -06:00
parent 0388d428a6
commit ec099a0077
2 changed files with 26 additions and 3 deletions

View File

@ -200,6 +200,3 @@ DEPENDENCIES
uglifier (>= 1.3.0)
unitwise (~> 2.0.0)
web-console (~> 2.0)
BUNDLED WITH
1.10.6

View File

@ -2,6 +2,22 @@ module UnitConversion
UNIT_PARSING_REGEX = /^(?<value>(?:-?[0-9]+)?(?:\.?[0-9]*)?)\s*(?<unit>[a-z\/.\-()0-9]+)$/
UNIT_ALIASES = {
cup: %w(cups c),
tablespoon: %w(tbsp tbs tablespoons),
teaspoon: %w(tsp teaspoons),
ounce: %w(oz ounces),
pound: %w(pounds lb lbs),
pint: %w(pints),
quart: %w(quarts),
gallon: %w(gallons ga),
gram: %w(grams g),
kilogram: %w(kilograms kg)
}
UNIT_ALIAS_MAP = Hash[UNIT_ALIASES.map { |unit, values| values.map { |v| [v, unit] } }.flatten(1)]
class UnparseableUnitError < StandardError
end
@ -28,5 +44,15 @@ module UnitConversion
unit.compatible_with? Unitwise(1, 'g/ml')
end
def normalize_unit_names(unit_description)
result = unit_description.dup
result = result.downcase.gsub(/[a-z]+/) do |match|
UNIT_ALIAS_MAP[match] || match
end
result
end
end
end