class Measurb::Dimension

Base class for defined dimensions to inherit from.

Attributes

abbrev[R]
dimension_name[R]
precision[R]
value[R]

Public Class Methods

new(value, precision = DEFAULT_PRECISION) click to toggle source

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

+(other) click to toggle source

Add another dimension

@param other [Measurb::Dimension] @return [Measurb::Dimension]

# File lib/measurb/dimension.rb, line 27
def +(other)
  arithmetic(:+, other)
end
-(other) click to toggle source

Subtract another dimension

@param other [Measurb::Dimension] @return [Measurb::Dimension]

# File lib/measurb/dimension.rb, line 35
def -(other)
  arithmetic(:-, other)
end
<=>(other) click to toggle source

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
eql?(other) click to toggle source

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
inspect() click to toggle source

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

arithmetic(op, other) click to toggle source

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
fix_value(value, precision) click to toggle source

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
to_self(other) click to toggle source

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