units 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ Units
2
+ Copyright 2005, Lucas Carlson
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1,79 @@
1
+ ==Welcome to Units
2
+
3
+ This is a package for people that want units for their numbers. For all of the conversions provided in units/standard, please see Numeric.
4
+
5
+ == Download
6
+
7
+ * http://rubyforge.org/projects/units
8
+ * gem install units
9
+ * svn co http://rufy.com/svn/units/trunk
10
+
11
+ ==Basic Usage
12
+ require 'units/standard'
13
+ 1.lb.to_ounces # => 16.0
14
+
15
+ require 'units/currency'
16
+ 1.euro.usd # => 1.2545
17
+
18
+ 1.usd.unit # => :usd
19
+ 1.usd.to_yen # => 108.9 # this information is grabbed on the fly
20
+ 1.usd.to_yet.unit # => :yen
21
+
22
+ ==Comparing Units with Rails' ActiveSupport
23
+
24
+ # What Rails' ActiveSupport does
25
+ # =====
26
+ 1.hour # => 3600
27
+ 1.hour.to_i # => 3600
28
+ 1.hour.minutes # => 216000 <-- This is non-sense
29
+ 1.hour.hour # => 12960000 <-- This is even more non-sense
30
+
31
+ # What Units does
32
+ # =====
33
+ 1.hour # => 1
34
+ 1.hour.unit # => :hours
35
+ 1.hour.to_i # => 3600
36
+ 1.hour.to_seconds # => 3600
37
+ 1.hour.minutes # => 60
38
+ 1.hour.hour # => 1 <-- this makes sense, there is 1 hour in an hour
39
+ 1.foot.inches # => 12
40
+
41
+ == How to Write Your Own Conversions
42
+ class Numeric
43
+ # Choose an arbitrary unit to be 1.0 and provide conversions for the other units
44
+ # =====
45
+ add_unit_conversions( :weight => {
46
+ :pounds => 1.0,
47
+ :ounces => 0.0625,
48
+ :kilograms => 0.45359237
49
+ }
50
+ )
51
+
52
+ # This is optional and for convenience only
53
+ # =====
54
+ add_unit_aliases( :weight => {
55
+ :pounds => [ :pound, :lb, :lbs ],
56
+ :ounces => [ :ounce, :oz ],
57
+ :kilograms => [ :kilogram, :kg, kgs ]
58
+ }
59
+ )
60
+
61
+ # Add dynamic lookups
62
+ add_unit_conversions :currency => :lookup_currency
63
+
64
+ def lookup_currency(old, new)
65
+ # return conversion from SOAP calls
66
+ end
67
+
68
+ def lookup_currency_include?(unit)
69
+ # check if a unit is a valid conversion externally
70
+ end
71
+ end
72
+
73
+ 1.pound.to_ounces # => 16.0
74
+
75
+ == Authors
76
+ * Lucas Carlson (mailto:lucas@rufy.com)
77
+ * John Butler (mailto:john@likealightbulb.com)
78
+
79
+ This library is released under the terms of the BSD license. See LICENSE for more details.
@@ -0,0 +1,91 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'rake/testtask'
4
+ require 'rake/rdoctask'
5
+ require 'rake/gempackagetask'
6
+ require 'rake/contrib/rubyforgepublisher'
7
+
8
+ PKG_VERSION = "1.0.0"
9
+
10
+ PKG_FILES = FileList[
11
+ "lib/**/*", "bin/*", "test/**/*", "[A-Z]*", "Rakefile", "doc/**/*"
12
+ ]
13
+
14
+ desc "Default Task"
15
+ task :default => [ :test ]
16
+
17
+ # Run the unit tests
18
+ desc "Run all unit tests"
19
+ Rake::TestTask.new("test") { |t|
20
+ t.libs << "lib"
21
+ t.pattern = 'test/*/*_test.rb'
22
+ t.verbose = true
23
+ }
24
+
25
+ # Make a console, useful when working on tests
26
+ desc "Generate a test console"
27
+ task :console do
28
+ verbose( false ) { sh "irb -I lib/ -r 'units/standard' -r 'units/currency'" }
29
+ end
30
+
31
+ # Genereate the RDoc documentation
32
+ desc "Create documentation"
33
+ Rake::RDocTask.new("doc") { |rdoc|
34
+ rdoc.title = "Ruby Units"
35
+ rdoc.rdoc_dir = 'html'
36
+ rdoc.rdoc_files.include('README')
37
+ rdoc.rdoc_files.include('LICENSE')
38
+ rdoc.rdoc_files.include('lib/**/*.rb')
39
+ }
40
+
41
+ # Genereate the package
42
+ spec = Gem::Specification.new do |s|
43
+
44
+ #### Basic information.
45
+
46
+ s.name = 'units'
47
+ s.version = PKG_VERSION
48
+ s.summary = <<-EOF
49
+ A general way to add units and conversion ability to numbers in Ruby.
50
+ EOF
51
+ s.description = <<-EOF
52
+ A general way to add units and conversion ability to numbers in Ruby.
53
+ EOF
54
+
55
+ #### Which files are to be included in this gem? Everything! (Except CVS directories.)
56
+
57
+ s.files = PKG_FILES
58
+
59
+ #### Load-time details: library and application (you will need one or both).
60
+
61
+ s.require_path = 'lib'
62
+
63
+ #### Documentation and testing.
64
+
65
+ s.has_rdoc = true
66
+
67
+ #### Author and project details.
68
+
69
+ s.author = "Lucas Carlson"
70
+ s.email = "lucas@rufy.com"
71
+ s.homepage = "http://rubyforge.org/projects/units/"
72
+ end
73
+
74
+ Rake::GemPackageTask.new(spec) do |pkg|
75
+ pkg.need_zip = true
76
+ pkg.need_tar = true
77
+ end
78
+
79
+ desc "Report code statistics (KLOCs, etc) from the application"
80
+ task :stats do
81
+ require 'code_statistics'
82
+ CodeStatistics.new(
83
+ ["Library", "lib"],
84
+ ["Units", "test"]
85
+ ).to_s
86
+ end
87
+
88
+ desc "Publish new documentation"
89
+ task :publish do
90
+ Rake::RubyForgePublisher.new('units', 'cardmagic').upload
91
+ end
@@ -0,0 +1,28 @@
1
+ #--
2
+ # Copyright (c) 2005 Lucas Carlson
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ #++
23
+ # Author:: Lucas Carlson (mailto:lucas@rufy.com)
24
+ # Author:: John Butler (mailto:john@likealightbulb.com)
25
+ # Copyright:: Copyright (c) 2005 Lucas Carlson
26
+ # License:: LGPL
27
+
28
+ require 'units/base'
@@ -0,0 +1,173 @@
1
+ class UnitsError < StandardError #:nodoc:
2
+ end
3
+
4
+ module Units
5
+ attr_reader :unit, :kind
6
+ alias :units :unit
7
+
8
+ # The heart of unit conversion, it will handle methods like: to_seconds and cast the number accordingly.
9
+ def method_missing(symbol, *args)
10
+ symbol = symbol.to_s.sub(/^to_/,'').intern if symbol.to_s =~ /^to_.+/
11
+
12
+ to_kind, to_unit = lookup_unit(symbol)
13
+
14
+ # If there is a kind and this is conversion and the aliases include the provided symbol, convert
15
+ if to_kind && to_unit && self.class.all_unit_aliases(to_kind).include?(symbol)
16
+ from_unit = (@unit || to_unit)
17
+ from_kind = lookup_unit(from_unit).first
18
+
19
+ if from_kind != to_kind
20
+ raise UnitsError, "invalid conversion, cannot convert #{from_unit} (a #{from_kind}) to #{to_unit} (a #{to_kind})"
21
+
22
+ else
23
+ # The reason these numbers have to be floats instead of integers is that all similar integers are the same ones
24
+ # in memory, so that @kind and @unit couldn't be different for different numbers
25
+ case self.class.unit_conversions[to_kind]
26
+ when Hash
27
+ result = Float( self * self.class.unit_conversions[from_kind][from_unit] / self.class.unit_conversions[to_kind][to_unit] )
28
+ when Symbol
29
+ result = Float( self * send(self.class.unit_conversions[to_kind], from_unit, to_unit) )
30
+ end
31
+ end
32
+
33
+ result.instance_eval do
34
+ @unit = to_unit
35
+ @kind = to_kind
36
+ end
37
+
38
+ return result
39
+ else
40
+ super
41
+ end
42
+ end
43
+
44
+ private
45
+
46
+ # lookup a kind and base unit (like [:volume, :liters]) when you input :liter
47
+ def lookup_unit(symbol)
48
+ self.class.unit_conversions.keys.each do |kind|
49
+ if Symbol === self.class.unit_conversions[kind]
50
+ return kind, symbol if send(:"#{ self.class.unit_conversions[kind] }_include?", symbol)
51
+ else
52
+ if self.class.unit_conversions[kind].include? symbol
53
+ return kind, symbol
54
+ else
55
+ s = self.class.unit_aliases[kind].find { |k,v| v.include? symbol }
56
+ return kind, s[0] if s
57
+ end
58
+ end
59
+ end
60
+ return nil, nil
61
+ end
62
+
63
+ module ClassMethods #:nodoc:
64
+ def unit_conversions() @@unit_conversions end
65
+ def unit_aliases() @@unit_aliases end
66
+ def add_unit_conversions(hash={}) unit_conversions.update(hash) end
67
+ def add_unit_aliases(hash={}) unit_aliases.update(hash) end
68
+
69
+ def init_units
70
+ @@unit_conversions = Hash.new
71
+ @@unit_aliases = Hash.new
72
+ end
73
+
74
+ def all_unit_aliases(kind)
75
+ results = Array.new
76
+ results += @@unit_conversions[kind].keys rescue nil
77
+ results += @@unit_aliases[kind].to_a.flatten rescue nil
78
+
79
+ return results.uniq
80
+ end
81
+ end
82
+
83
+ def self.append_features(base) #:nodoc:
84
+ super
85
+ base.extend ClassMethods
86
+ base.init_units
87
+ end
88
+ end
89
+
90
+ class Numeric
91
+ include Units
92
+ end
93
+
94
+ class Float
95
+ alias :add :+
96
+ # Add only numbers that both have units or both don't have units
97
+ def +(other)
98
+ if Float === other && kind && other.kind
99
+ add_with_units( unit == other.unit ? other : other.send(unit) )
100
+
101
+ elsif Numeric === other && (kind || other.kind) && (kind.nil? || other.kind.nil?)
102
+ raise UnitsError, "cannot add a number without units to one with units"
103
+
104
+ else
105
+ add other
106
+ end
107
+ end
108
+ def add_with_units(other)
109
+ add(other).send(unit)
110
+ end
111
+
112
+ alias :multiply :*
113
+ # CURRENTLY: Scalar multiplication (a number with a unit to a number without a unit)
114
+ # TO COME: Non-scalar multiplication
115
+ # This will require keeping track of the exponents, like:
116
+ # meters is [:meters, 1], square inches is [:inches, 2], cubic mililiters is [:milileters, 3]
117
+ # And then we can get rid of the silly :m3's in the volume conversion as well
118
+ # as add new units like:
119
+ # :joules => [[:kilograms, 1], [:meters, 1], [:seconds, -2]]
120
+ def *(other)
121
+ if Numeric === other && kind && other.kind
122
+ raise UnitsError, "currently cannot mutiply two numers with units, try scalar multiplication instead"
123
+
124
+ elsif Numeric === other && kind.nil? && other.kind.nil?
125
+ multiply other
126
+
127
+ else
128
+ multiply_with_units other
129
+ end
130
+ end
131
+ def multiply_with_units(other)
132
+ multiply(other).send(unit || other.unit)
133
+ end
134
+ end
135
+
136
+ class Fixnum
137
+ alias :add :+
138
+ # Raise an error if the other number has a unit
139
+ def +(other)
140
+ if Numeric === other && other.kind
141
+ raise UnitsError, "cannot add a number without units to one with units"
142
+
143
+ else
144
+ add other
145
+ end
146
+ end
147
+
148
+ alias :multiply :*
149
+ # Allow for scalar multiplication
150
+ def *(other)
151
+ if Numeric === other && other.kind
152
+ multiply_with_units other
153
+
154
+ else
155
+ multiply other
156
+ end
157
+ end
158
+ def multiply_with_units(other)
159
+ multiply(other).send(unit || other.unit)
160
+ end
161
+ end
162
+
163
+ class String
164
+ alias :multiply :*
165
+ # Cannot multiply a String by anything Numeric with units
166
+ def *(other)
167
+ if Numeric === other && other.kind
168
+ raise UnitsError, "cannot multiply a String by anything Numeric with units"
169
+ else
170
+ multiply other
171
+ end
172
+ end
173
+ end
@@ -0,0 +1,28 @@
1
+ require 'units/base'
2
+ require 'soap/wsdlDriver'
3
+
4
+ class Numeric
5
+ # Clear the cache so that any previous grabs of the currency do not appear
6
+ def self.clear_currency_rates() @@currency_rates = Hash.new end
7
+ # A cache of the currency conversion rates
8
+ def self.currency_rates() @@currency_rates end
9
+
10
+ private
11
+
12
+ @@currency_rates = Hash.new
13
+ @@currency_converter = SOAP::WSDLDriverFactory.new("http://www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl").createDriver
14
+ @@currency_countries = { :euro => "euro", :brl =>"brazil", :frf =>"france", :marks =>"germany", :veb =>"venezuela", :jpy =>"japan", :dinars =>"tunisia", :kroner =>"norway", :bmd =>"bermuda", :eek =>"estonia", :jod =>"jordan", :shekels =>"israel", :idr =>"indonesia", :fim =>"finland", :sdd =>"sudan", :drachmae =>"greece", :esp =>"spain", :zlotych =>"poland", :markkaa =>"finland", :try =>"turkey", :rupiahs =>"indonesia", :cyp =>"cyprus", :pesetas =>"spain", :pte =>"portugal", :rubles =>"russia", :isk =>"iceland", :tnd =>"tunisia", :mxn =>"mexico", :lkr =>"sri lanka", :huf =>"hungary", :sgd =>"singapore", :dop =>"dominican republic", :fjd =>"fiji", :mur =>"mauritius", :php =>"philippines", :bbd =>"barbados", :gbp =>"united kingdom", :zmk =>"zambia", :vnd =>"vietnam", :iqd =>"iraq", :rupees =>"sri lanka", :shillings =>"kenya", :hrk =>"croatia", :bhd =>"bahrain", :nlg =>"netherlands", :schillings =>"austria", :sit =>"slovenia", :baht =>"thailand", :koruny =>"slovakia", :twd =>"taiwan", :aud =>"australia", :pkr =>"pakistan", :luf =>"luxembourg", :bef =>"belgium", :crc =>"costa rica", :bdt =>"bangladesh", :czk =>"czech republic", :iep =>"ireland", :qar =>"qatar", :cad =>"canada", :ats =>"austria", :all =>"albania", :lira =>"turkey", :kwd =>"kuwait", :riyals =>"saudi arabia", :rub =>"russia", :sar =>"saudi arabia", :kuna =>"croatia", :nok =>"norway", :usd =>"united states", :omr =>"oman", :enminbi =>"china", :grd =>"greece", :krooni =>"estonia", :taka =>"bangladesh", :lire =>"italy", :cny =>"china", :kes =>"kenya", :itl =>"italy", :dong =>"vietnam", :kronor =>"sweden", :pln =>"poland", :guilders =>"netherlands", :colones =>"costa rica", :inr =>"india", :clp =>"chile", :dem =>"germany", :tolars =>"slovenia", :hkd =>"hong kong", :myr =>"malaysia", :cop =>"colombia", :dkk =>"denmark", :sek =>"sweden", :rol =>"romania", :liri =>"malta", :pesos =>"mexico", :kwacha =>"zambia", :kronur =>"iceland", :mtl =>"malta", :ron =>"romania", :escudos =>"portugal", :dzd =>"algeria", :ars =>"argentina", :skk =>"slovakia", :bolivares =>"venezuela", :trl =>"turkey", :dollars =>"united states", :francs =>"switzerland", :afghanis =>"afghanistan", :lei =>"romania", :mad =>"morocco", :eur =>"euro", :ringgits =>"malaysia", :chf =>"switzerland", :egp =>"egypt", :leke =>"albania", :rials =>"oman", :ils =>"israel", :lbp =>"lebanon", :forint =>"hungary", :afa =>"afghanistan", :yen =>"japan", :reais =>"brazil", :thb =>"thailand" }
15
+
16
+ add_unit_conversions :currency => :lookup_currency
17
+ add_unit_aliases :currency => @@currency_countries.keys.inject({}) { |hash, value| hash.update value => [] }
18
+
19
+ def lookup_currency(from, to)
20
+ cache_key = :"#{from}_to_#{to}"
21
+ @@currency_rates[cache_key] ||= @@currency_converter.getRate(@@currency_countries[from], @@currency_countries[to])
22
+ return @@currency_rates[cache_key]
23
+ end
24
+
25
+ def lookup_currency_include?(unit)
26
+ @@currency_countries.include? unit.to_s.downcase.intern
27
+ end
28
+ end
@@ -0,0 +1,147 @@
1
+ require 'units/base'
2
+
3
+ class Numeric
4
+ WEIGHT = {
5
+ :pounds => 1.0,
6
+ :ounces => 0.0625,
7
+ :kilograms => 0.45359237,
8
+ :grams => 453.59237
9
+ }
10
+ WEIGHT_ALIASES = {
11
+ :pounds => [ :lb, :lbs, :pound ],
12
+ :ounces => [ :oz, :ozs, :ounce ],
13
+ :kilograms => [ :kg, :kgs, :kilogram ],
14
+ :grams => [ :gm, :gms, :gram ]
15
+ }
16
+ VOLUME = {
17
+ :liters => 0.00492892161,
18
+ :hectoliters => 0.0000492892161,
19
+ :deciliters => 0.0492892161,
20
+ :centiliters => 0.492892161,
21
+ :milliliters => 4.92892161,
22
+ :microliters => 4928.92161,
23
+ :cubic_centimeters => 3785.4118,
24
+ :cubic_millimeters => 3785411.8,
25
+ :cubic_meters => 0.0037854118,
26
+ :cubic_decimeters => 3.7854118,
27
+ :cubic_feet => 0.133680556,
28
+ :cubic_inches => 231.000001,
29
+ :cubic_yards => 0.00495113171,
30
+ :gallons => 1,
31
+ :quarts => 4,
32
+ :pints => 8,
33
+ :cups => 16,
34
+ :gills => 32,
35
+ :fluid_ounces => 128,
36
+ :tablespoons => 256,
37
+ :teaspoons => 768,
38
+ :fluid_drams => 1024,
39
+ :minims => 61440
40
+ }
41
+ VOLUME_ALIASES = {
42
+ :liters => [ :liter, :l ],
43
+ :hectoliters => [ :hectoliter, :hl ],
44
+ :deciliters => [ :deciliter, :dl ],
45
+ :centiliters => [ :centiliter, :cl ],
46
+ :milliliters => [ :milliliter, :ml ],
47
+ :microliters => [ :microliter, :ul ],
48
+ :cubic_centimeters => [ :cubic_centimeter, :cm3 ],
49
+ :cubic_millimeters => [ :cubic_millimeter, :mm3 ],
50
+ :cubic_meters => [ :cubic_meter, :m3 ],
51
+ :cubic_decimeters => [ :cubic_decimeter, :dm3 ],
52
+ :cubic_feet => [ :cubic_foot, :f3 ],
53
+ :cubic_inches => [ :cubic_inch, :i3 ],
54
+ :cubic_yards => [ :cubic_yard, :y3 ],
55
+ :gallons => [ :gallon, :gal, :gals ],
56
+ :quarts => [ :quart, :qt, :qts ],
57
+ :pints => [ :pint, :pt, :pts ],
58
+ :cups => [ :cup ],
59
+ :gills => [ :gill ],
60
+ :fluid_ounces => [ :fluid_oz, :fluid_ozs ],
61
+ :tablespoons => [ :tablespoon, :tbsp ],
62
+ :teaspoons => [ :teaspoon, :tsp ],
63
+ :fluid_drams => [ :fluid_dram ],
64
+ :minims => [ :minim ]
65
+ }
66
+ TIME = {
67
+ :seconds => 1.0,
68
+ :minutes => 60.0,
69
+ :hours => 3600.0,
70
+ :days => 86400.0,
71
+ :weeks => 604800.0,
72
+ :years => 31449600.0
73
+ }
74
+ TIME_ALIASES = {
75
+ :seconds => [ :sec, :second ],
76
+ :minutes => [ :min, :mins, :minute ],
77
+ :hours => [ :hour ],
78
+ :days => [ :day ],
79
+ :weeks => [ :week ],
80
+ :years => [ :year ]
81
+ }
82
+ SIZE = {
83
+ :bytes => 1.0,
84
+ :bits => 8.0,
85
+ :kilobytes => 1024.0,
86
+ :megabytes => 1048576.0,
87
+ :gigabytes => 1073741824.0,
88
+ :terabytes => 1099511627776.0,
89
+ :petabytes => 1.12589991e15
90
+ }
91
+ SIZE_ALIASES = {
92
+ :bits => [ :bit ],
93
+ :bytes => [ :b, :byte ],
94
+ :kilobytes => [ :kb, :kilobyte ],
95
+ :megabytes => [ :mb, :megabyte ],
96
+ :gigabytes => [ :gb, :gigabyte ],
97
+ :terabytes => [ :tb, :terabyte ],
98
+ :petabytes => [ :pb, :petabyte ]
99
+ }
100
+ LENGTH = {
101
+ :inches => 1.0,
102
+ :feet => 12.0,
103
+ :meters => 39.3700787,
104
+ :kilometers => 39370.0787,
105
+ :milimeters => 0.0393700787,
106
+ :centimeters => 0.393700787,
107
+ :miles => 63360.0
108
+ }
109
+ LENGTH_ALIASES = {
110
+ :inches => [ :inch ],
111
+ :feet => [ :foot ],
112
+ :miles => [ :mile ],
113
+ :meters => [ :m, :meter ],
114
+ :kilometers => [ :km, :kilometer ],
115
+ :milimeters => [ :mm, :milimeter ],
116
+ :centimeters => [ :cm, :centimeter ]
117
+ }
118
+
119
+ add_unit_conversions(
120
+ :weight => WEIGHT,
121
+ :volume => VOLUME,
122
+ :time => TIME,
123
+ :size => SIZE,
124
+ :length => LENGTH
125
+ )
126
+
127
+ add_unit_aliases(
128
+ :weight => WEIGHT_ALIASES,
129
+ :volume => VOLUME_ALIASES,
130
+ :time => TIME_ALIASES,
131
+ :size => SIZE_ALIASES,
132
+ :length => LENGTH_ALIASES
133
+ )
134
+
135
+ end
136
+
137
+ class Float #:nodoc:
138
+ alias :_to_i :to_i
139
+ def to_i
140
+ case kind
141
+ when :time
142
+ to_seconds._to_i
143
+ when :size
144
+ to_kilobytes._to_i
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,4 @@
1
+ $:.unshift(File.dirname(__FILE__) + '/../lib')
2
+
3
+ require 'test/unit'
4
+ require 'units/standard'
@@ -0,0 +1,70 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class BaseTest < Test::Unit::TestCase
4
+ def setup
5
+ @num1 = 1234.5678
6
+ @num2 = 9876.5432
7
+
8
+ [@num1, @num2].each do |n|
9
+ n.instance_eval do
10
+ self.class.add_unit_conversions(
11
+ :test_kind => {
12
+ :bases => 1.0,
13
+ :biggers => 10.0
14
+ },
15
+ :bad_kind => {
16
+ :flavors => 1.0,
17
+ }
18
+ )
19
+ self.class.add_unit_aliases(
20
+ :test_kind => {
21
+ :bases => [ :base ],
22
+ :biggers => [ :bigger ]
23
+ }
24
+ )
25
+ end
26
+ end
27
+ end
28
+
29
+ def test_add_unit_conversions
30
+ assert_equal :test_kind, @num1.to_bases.kind
31
+ assert_equal :bad_kind, @num2.flavors.kind
32
+ assert_equal :bases, @num1.to_bases.unit
33
+ assert_equal :bases, @num1.to_bases.to_bases.unit
34
+ assert_equal :biggers, @num2.to_biggers.unit
35
+ end
36
+
37
+ def test_add_unit_aliases
38
+ assert_equal :bases, @num1.to_base.unit
39
+ assert_equal :biggers, @num2.to_bigger.unit
40
+ end
41
+
42
+ def test_adding
43
+ assert_equal 11111.111, @num1 + @num2
44
+ assert_equal 11111.111, @num2 + @num1
45
+
46
+ assert_equal 99999.9998, @num1.to_base + @num2.to_biggers
47
+ assert_equal 22222.2212, @num2.to_base + @num1.to_biggers
48
+
49
+ assert_equal :bases, (@num1.to_base + @num2.to_biggers).units
50
+ assert_equal :biggers, (@num1.to_biggers + @num2.to_bases).units
51
+
52
+ assert_raise(UnitsError) { @num1.to_base + 2 }
53
+ assert_raise(UnitsError) { 5 + @num1.to_base }
54
+ assert_raise(UnitsError) { @num1.to_base + 2.0 }
55
+ assert_raise(UnitsError) { 5.0 + @num1.to_base }
56
+ end
57
+
58
+ def test_multiplying
59
+ assert_equal 2469.1356, @num1 * 2
60
+ assert_equal 2469.1356, @num1.to_base * 2
61
+ assert_equal nil, (@num1 * 2).units
62
+ assert_equal :bases, (@num1.to_base * 2).units
63
+
64
+ assert_raise(UnitsError) { @num1.to_base * @num2.to_base }
65
+ assert_raise(TypeError) { @num1.to_base * "string" }
66
+ assert_raise(UnitsError) { "string" * @num1.to_base }
67
+ assert_equal "stringstringstring", "string" * 3.0
68
+ end
69
+
70
+ end
@@ -0,0 +1,12 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+ require 'units/currency'
3
+
4
+ class CurrencyTest < Test::Unit::TestCase
5
+ def test_euro_to_dollar
6
+ assert_equal Hash.new, Numeric.currency_rates
7
+
8
+ assert_in_delta 1.5, 1.euro.usd, 0.5
9
+ assert Numeric.currency_rates[:euro_to_euro] == 1.0
10
+ assert_equal 2, Numeric.currency_rates.size
11
+ end
12
+ end
@@ -0,0 +1,33 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class StandardTest < Test::Unit::TestCase
4
+ def test_weight
5
+ assert_equal 64.0, 4.pounds.to_ozs
6
+ assert_equal :ounces, (4.pounds.to_ozs).units
7
+ assert_equal :weight, (4.pounds.to_ozs).kind
8
+ end
9
+
10
+ def test_volume
11
+ assert_equal 4.0, 1.cup.to_quarts
12
+ assert_equal :quarts, (1.cup.to_quarts).units
13
+ assert_equal :volume, (1.cup.to_quarts).kind
14
+ end
15
+
16
+ def test_time
17
+ assert_equal 60.0, 1.minute.to_seconds
18
+ assert_equal :seconds, (1.minute.to_seconds).unit
19
+ assert_equal :time, (1.minute.to_seconds).kind
20
+ end
21
+
22
+ def test_size
23
+ assert_equal 1024.0, 1.mb.to_kb
24
+ assert_equal :kilobytes, (1.mb.to_kb).units
25
+ assert_equal :size, (1.mb.to_kb).kind
26
+ end
27
+
28
+ def test_length
29
+ assert_equal 2.5400000025908, 1.inch.to_cm
30
+ assert_equal :centimeters, (1.inch.to_cm).units
31
+ assert_equal :length, (1.inch.to_cm).kind
32
+ end
33
+ end
metadata ADDED
@@ -0,0 +1,49 @@
1
+ --- !ruby/object:Gem::Specification
2
+ rubygems_version: 0.8.10
3
+ specification_version: 1
4
+ name: units
5
+ version: !ruby/object:Gem::Version
6
+ version: 1.0.0
7
+ date: 2005-09-05
8
+ summary: A general way to add units and conversion ability to numbers in Ruby.
9
+ require_paths:
10
+ - lib
11
+ email: lucas@rufy.com
12
+ homepage: http://rubyforge.org/projects/units/
13
+ rubyforge_project:
14
+ description: A general way to add units and conversion ability to numbers in Ruby.
15
+ autorequire:
16
+ default_executable:
17
+ bindir: bin
18
+ has_rdoc: true
19
+ required_ruby_version: !ruby/object:Gem::Version::Requirement
20
+ requirements:
21
+ -
22
+ - ">"
23
+ - !ruby/object:Gem::Version
24
+ version: 0.0.0
25
+ version:
26
+ platform: ruby
27
+ authors:
28
+ - Lucas Carlson
29
+ files:
30
+ - lib/units
31
+ - lib/units.rb
32
+ - lib/units/base.rb
33
+ - lib/units/currency.rb
34
+ - lib/units/standard.rb
35
+ - test/test_helper.rb
36
+ - test/units
37
+ - test/units/base_test.rb
38
+ - test/units/currency_test.rb
39
+ - test/units/standard_test.rb
40
+ - LICENSE
41
+ - Rakefile
42
+ - README
43
+ test_files: []
44
+ rdoc_options: []
45
+ extra_rdoc_files: []
46
+ executables: []
47
+ extensions: []
48
+ requirements: []
49
+ dependencies: []