Class: SY::Mapping

Inherits:
Object
  • Object
show all
Defined in:
lib/sy/mapping.rb

Overview

Represents relationship of two quantities. Provides import and export conversion closures. Instances are immutable and have 2 attributes:

  • im - import closure, converting amount of quantity 1 into quantity 2

  • ex - export closure, converting amount of quantity 2 into quantity 1

Convenience methods for mapping magnitudes are:

  • import - like im, but operates on magnitudes

  • export - like ex, but operates on magnitudes

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(arg) ⇒ Mapping

Takes either a magnitude (1 argument), or 2 named arguments :im, :ex speficying amount import and export closure. For a magnitude, these closures are constructed automatically, assuming simple ratio rule.



27
28
29
30
31
32
33
34
35
36
# File 'lib/sy/mapping.rb', line 27

def initialize arg
  case arg
  when Hash then
    @ex, @im = arg[:ex], arg[:im]
  else
    @ratio = r = arg
    @ex = lambda { |amount1| amount1 * r }
    @im = lambda { |amount2| amount2 / r }
  end
end

Instance Attribute Details

#exObject (readonly)

Returns the value of attribute ex.



21
22
23
# File 'lib/sy/mapping.rb', line 21

def ex
  @ex
end

#imObject (readonly)

Returns the value of attribute im.



21
22
23
# File 'lib/sy/mapping.rb', line 21

def im
  @im
end

#ratioObject (readonly)

Returns the value of attribute ratio.



21
22
23
# File 'lib/sy/mapping.rb', line 21

def ratio
  @ratio
end

Class Method Details

.identityObject



16
17
18
# File 'lib/sy/mapping.rb', line 16

def identity
  new 1
end

Instance Method Details

#*(r2) ⇒ Object

mapping composition



55
56
57
58
59
60
61
62
63
# File 'lib/sy/mapping.rb', line 55

def * r2 # mapping composition
  

#**(n) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/sy/mapping.rb', line 69

def ** n
  

#/(r2) ⇒ Object



65
66
67
# File 'lib/sy/mapping.rb', line 65

def / r2
  self * r2.inverse
end

#export(magnitude, to_quantity) ⇒ Object



42
43
44
# File 'lib/sy/mapping.rb', line 42

def export magnitude, to_quantity
  to_quantity.magnitude @ex.( magnitude.amount )
end

#import(magnitude, from_quantity) ⇒ Object



38
39
40
# File 'lib/sy/mapping.rb', line 38

def import magnitude, from_quantity
  from_quantity.magnitude @im.( magnitude.amount )
end

#inverseObject



46
47
48
49
50
51
52
53
# File 'lib/sy/mapping.rb', line 46

def inverse
  self.class.new begin
                   1 / @ratio
                 rescue NoMethodError, TypeError
                   i, e = im, ex
                   { im: e, ex: i } # swap closures
                 end
end