class Measurb::Dimension
Base class for defined dimensions to inherit from.
Attributes
Public Class Methods
Initialize the dimension
@param value [Numeric] Numeric value to wrap @param precision [Integer] Precision of decimal places @return [Measurb::Dimension]
# File lib/measurb/dimension.rb, line 17 def initialize(value, precision = DEFAULT_PRECISION) @precision = precision @original_value = value @value = fix_value(value, precision) end
Public Instance Methods
Add another dimension
@param other [Measurb::Dimension] @return [Measurb::Dimension]
# File lib/measurb/dimension.rb, line 27 def +(other) arithmetic(:+, other) end
Subtract another dimension
@param other [Measurb::Dimension] @return [Measurb::Dimension]
# File lib/measurb/dimension.rb, line 35 def -(other) arithmetic(:-, other) end
Compare with another dimension
@param other [Measurb::Dimension] @return [-1, 0, 1]
# File lib/measurb/dimension.rb, line 43 def <=>(other) value <=> to_self(other).value end
Check type and value quality with another dimension
@param other [Measurb::Dimension] @return [Boolean]
# File lib/measurb/dimension.rb, line 51 def eql?(other) self.class == other.class && self == other end
Get the inspect string
@return [String]
# File lib/measurb/dimension.rb, line 58 def inspect "#{value} #{self.class.abbrev || self.class.dimension_name}" end
Private Instance Methods
Perform an arithmetic operation `name` with `other`, keeping the smallest precision of the two dimensions.
@param op [Symbol] Name of the arithmetic operation @param other [Measurb::Dimension] @return [Measurb::Dimension]
# File lib/measurb/dimension.rb, line 70 def arithmetic(op, other) least_precision = [precision, other.precision].min new_value = value.__send__(op, to_self(other).value) self.class.new(new_value, least_precision) end
Adjust a value to a given decimal precision
@param value [Numeric] @param precision [Integer] Precision of decimal places
# File lib/measurb/dimension.rb, line 88 def fix_value(value, precision) modifier = (10 ** precision).to_f (value * modifier).round / modifier end
Coerce other dimension to own class
@param other [Measurb::Dimension] @return [self.class]
# File lib/measurb/dimension.rb, line 80 def to_self(other) other.__send__("to_#{self.class.dimension_name}") end