Module: Stick::Units

Included in:
Constants::CGS, Constants::MKS
Defined in:
lib/stick/units.rb,
lib/stick/currency.rb,
lib/stick/units/base.rb,
lib/stick/units/units.rb,
lib/stick/units/loaders.rb,
lib/stick/units/currency.rb

Defined Under Namespace

Modules: Config Classes: BaseUnit, BinaryLoader, Converter, CurrencyLoader, IECBinaryLoader, LengthLoader, Loader, Regexps, SILoader, StandardLoader, Unit, Value

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &blk) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/stick/units/base.rb', line 75

def method_missing(m, *args, &blk)
  if args.length == 1
    args[0] = (::Stick::Units::Converter.converter(args[0]) rescue nil) if not args[0].is_a? ::Stick::Units::Converter
    return ::Stick::Units::Unit.new({m => 1}, args[0]) if args[0] && args[0].registered?(m)
  elsif (::Stick::Units::Converter.current.registered?(m) rescue false)
    raise ::ArgumentError, "Wrong number of arguments" if args.length != 0
    return ::Stick::Units::Unit.new({m => 1}, ::Stick::Units::Converter.current)
  end
  ::Exception.with_clean_backtrace("method_missing") {
    super
  }
end

Class Method Details

.append_features(m) ⇒ Object



98
99
100
101
# File 'lib/stick/units/base.rb', line 98

def self.append_features(m)
  m.send(:extend, ::Stick::Units)
  super
end

.with_unit_converter(name, &blk) ⇒ Object

Executes the block with the current Converter changed to the given Converter. This allows to temporarily change the Converter used by default. A Converter object can be given, or the name of a registered Converter.

Example:

with_unit_converter(:uk) {
  puts 1.cwt.to(lb) # => 112.0 lb
}

with_unit_converter(:us) {
  puts 1.cwt.to(lb) # => 100.0 lb
}

See also Converter.current.



119
120
121
# File 'lib/stick/units/base.rb', line 119

def with_unit_converter(name, &blk) # :yields:
  ::Stick::Units::Converter.with_converter(name, &blk)
end

Instance Method Details

#const_missing(c) ⇒ Object



88
89
90
91
92
93
94
95
96
# File 'lib/stick/units/base.rb', line 88

def const_missing(c)
  if (::Stick::Units::Converter.current.registered?(c) rescue false)
    return ::Stick::Units::Unit.new({c => 1}, ::Stick::Units::Converter.current)
  else
    ::Exception.with_clean_backtrace("const_missing") {
      super
    }
  end
end