Module: Unitwise::Compatible

Included in:
Atom, Scale, Term, Unit
Defined in:
lib/unitwise/compatible.rb

Overview

Compatible is used to establish compatibility between units, terms, or measurements. This is done by determining the objects atomic composition represented as a Signed Multiset.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



7
8
9
10
11
# File 'lib/unitwise/compatible.rb', line 7

def self.included(base)
  base.send :include, Comparable
  base.send :include, Memoizable unless base < Memoizable
  base.send :memoize, :composition, :composition_string
end

Instance Method Details

#<=>(other) ⇒ -1 0 1

Compare whether the instance is greater, less than or equal to other.



54
55
56
57
58
# File 'lib/unitwise/compatible.rb', line 54

def <=>(other)
  if other.respond_to?(:composition) && compatible_with?(other)
    scalar <=> other.scalar
  end
end

#compatible_with?(other) ⇒ true false

Determine if this instance is similar to or compatible with other



47
48
49
# File 'lib/unitwise/compatible.rb', line 47

def compatible_with?(other)
  composition == other.composition
end

#compositionSignedMultiset

A representation of a unit based on the atoms it's derived from.



21
22
23
24
25
26
# File 'lib/unitwise/compatible.rb', line 21

def composition
  root_terms.reduce(SignedMultiset.new) do |s, t|
    s.increment(t.atom.dim, t.exponent) if t.atom
    s
  end
end

#composition_stringString

A string representation of a unit based on the atoms it's derived from



38
39
40
41
42
# File 'lib/unitwise/compatible.rb', line 38

def composition_string
  composition.sort.map do |k, v|
    v == 1 ? k.to_s : "#{k}#{v}"
  end.join('.')
end

#dimString

Define a default #dim for included classes.



31
32
33
# File 'lib/unitwise/compatible.rb', line 31

def dim
  composition_string
end

#initialize(*args) ⇒ Object



13
14
15
16
# File 'lib/unitwise/compatible.rb', line 13

def initialize(*args)
  super(*args)
  freeze
end