Class: Measurement::Unit

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-measurement/unit.rb

Defined Under Namespace

Classes: Builder

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Unit

Returns a new instance of Unit.



9
10
11
12
13
14
# File 'lib/ruby-measurement/unit.rb', line 9

def initialize(name)
  @name = name.to_s
  @aliases = Set.new
  @conversions = {}
  add_alias(name)
end

Instance Attribute Details

#aliasesObject (readonly)

Returns the value of attribute aliases.



5
6
7
# File 'lib/ruby-measurement/unit.rb', line 5

def aliases
  @aliases
end

#conversionsObject (readonly)

Returns the value of attribute conversions.



5
6
7
# File 'lib/ruby-measurement/unit.rb', line 5

def conversions
  @conversions
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/ruby-measurement/unit.rb', line 5

def name
  @name
end

Class Method Details

.[](unit_name) ⇒ Object



58
59
60
# File 'lib/ruby-measurement/unit.rb', line 58

def [](unit_name)
  @definitions[unit_name.to_s.downcase]
end

.[]=(unit_name, unit) ⇒ Object



62
63
64
# File 'lib/ruby-measurement/unit.rb', line 62

def []=(unit_name, unit)
  @definitions[unit_name.to_s.downcase] = unit
end

.define(unit_name, &block) ⇒ Object



54
55
56
# File 'lib/ruby-measurement/unit.rb', line 54

def define(unit_name, &block)
  Builder.new(unit_name, &block)
end

.namesObject



66
67
68
# File 'lib/ruby-measurement/unit.rb', line 66

def names
  @definitions.keys
end

Instance Method Details

#==(obj) ⇒ Object



47
48
49
50
51
# File 'lib/ruby-measurement/unit.rb', line 47

def ==(obj)
  obj.kind_of?(self.class) && name == obj.name && aliases == obj.aliases && conversions.all? do |key, proc|
    [-2.5, -1, 0, 1, 2.5].all? { |n| proc.call(n) == obj.conversions[key].call(n) }
  end
end

#add_alias(*args) ⇒ Object



16
17
18
19
20
21
# File 'lib/ruby-measurement/unit.rb', line 16

def add_alias(*args)
  args.each do |unit_alias|
    @aliases << unit_alias.to_s
    self.class[unit_alias] = self
  end
end

#add_conversion(unit_name, &block) ⇒ Object



23
24
25
# File 'lib/ruby-measurement/unit.rb', line 23

def add_conversion(unit_name, &block)
  @conversions[unit_name.to_s] = block
end

#conversion(unit_name) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ruby-measurement/unit.rb', line 27

def conversion(unit_name)
  unit = self.class[unit_name]
  return nil unless unit

  unit.aliases.each do |unit_alias|
    conversion = @conversions[unit_alias.to_s]
    return conversion if conversion
  end

  nil
end

#inspectObject



39
40
41
# File 'lib/ruby-measurement/unit.rb', line 39

def inspect
  to_s
end

#to_sObject



43
44
45
# File 'lib/ruby-measurement/unit.rb', line 43

def to_s
  name
end