Class: String

Inherits:
Object
  • Object
show all
Includes:
ActiveSupport::CoreExtensions::String::Inflections
Defined in:
lib/active_support/core_ext/string.rb,
lib/uom/measurement.rb

Overview

:nodoc:

Instance Method Summary collapse

Methods included from ActiveSupport::CoreExtensions::String::Inflections

#camelize, #classify, #constantize, #dasherize, #demodulize, #foreign_key, #humanize, #parameterize, #pluralize, #singularize, #tableize, #titleize, #underscore

Instance Method Details

#to_measurement(default_unit = nil) ⇒ Object

Returns the Measurement parsed from this string, e.g.:

"1 gm".to_measurement.unit #=> grams

If no unit is discernable from this string, then the default unit is used.

Raises MeasurementError if there is no unit in either this string or the argument.



96
97
98
99
100
101
102
103
104
105
106
# File 'lib/uom/measurement.rb', line 96

def to_measurement(default_unit=nil)
  stripped = strip.delete(',')
  quantity_s = stripped[/[.\d]*/]
  quantity = quantity_s =~ /\./ ? quantity_s.to_f : quantity_s.to_i
  unit_s = stripped[quantity_s.length..-1] if quantity_s.length < length
  unit_s ||= default_unit.to_s if default_unit
  raise UOM::MeasurementError.new("Unit could not be determined from #{self}") if unit_s.nil?
  unit_s = unit_s.sub('/', '_per_')
  unit = UOM::Unit.for(unit_s.strip.to_sym)
  UOM::Measurement.new(unit, quantity)
end

#to_measurement_quantity(unit = nil) ⇒ Object

Returns this String as a unitized quantity. If this is a numerical String, then it is returned as a Numeric. Commas and a non-numeric prefix are removed if present. Returns nil if this is not a measurement string. If unit is given, then this method converts the measurement to the given unit.



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/uom/measurement.rb', line 113

def to_measurement_quantity(unit=nil)
  # remove commas
  return delete(',').to_measurement_quantity(unit) if self[',']
  # extract the quantity portion
  quantity_s = self[/\d*\.?\d*/]
  return if quantity_s.nil? or quantity_s == '.'
  quantity = quantity_s['.'] ? quantity_s.to_f : quantity_s.to_i
  # extract the unit portion
  unit_s = self[/([[:alpha:]]+)(\s)?$/, 1]
  return quantity if unit_s.nil?
  # make the measurement
  msmt = "#{quantity} #{unit_s.downcase}".to_measurement
  # return the measurement quantity
  msmt = msmt.as(unit) if unit
  msmt.quantity
end