Module: Phys::UnitsMixin

Defined in:
lib/phys/units/units_mixin.rb

Overview

Defines method with unit name. Caution: Variable names may conflict with unit names.

Examples:

require 'phys/units'

Phys::UnitsMixin.module_eval do
  puts 123.4*km
  puts 23*mile/hr >> m/s
  puts h.to_si
  case mile/hr
  when m
    puts "length"
  when m/s
    puts "velocity"
  else
    puts "other"
  end
end

extend Phys::UnitsMixin

1*miles/hr >> m/s    #=> Phys::Quantity[0.44704,"m/s"]

Class Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object (private)



44
45
46
47
48
49
50
51
# File 'lib/phys/units/units_mixin.rb', line 44

def method_missing(method, *args, &block)
  if unit = Unit.find_unit(method)
    raise "argument must be empty" unless args.empty?
    Quantity.new(Rational(1), method, unit)
  else
    method_missing_units_alias(method, *args, &block)
  end
end

Class Method Details

.method_missing(method, *args, &block) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/phys/units/units_mixin.rb', line 44

def method_missing(method, *args, &block)
  if unit = Unit.find_unit(method)
    raise "argument must be empty" unless args.empty?
    Quantity.new(Rational(1), method, unit)
  else
    method_missing_units_alias(method, *args, &block)
  end
end

.method_missing_units_aliasObject



42
# File 'lib/phys/units/units_mixin.rb', line 42

alias method_missing_units_alias method_missing


53
54
55
56
57
58
59
60
61
62
# File 'lib/phys/units/units_mixin.rb', line 53

def print_units(unit=nil)
  Unit::LIST.each do |k,u|
    if unit.nil? || unit===u
      len = 32 - k.size
      len = 1 if len < 1
      puts k+" "*len+"#{u.expr}"
    end
  end
  nil
end