woahdae-units 1.0.2 → 1.0.3

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 who want units with 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 via a SOAP call
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.to_minutes # => 60
38
+ 1.hour.to_hours # => 1 <-- this makes sense, there is 1 hour in an hour
39
+ 1.foot.to_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.
data/Rakefile ADDED
@@ -0,0 +1,60 @@
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
+ begin
9
+ require 'jeweler'
10
+ Jeweler::Tasks.new do |gemspec|
11
+ gemspec.name = 'units'
12
+ gemspec.summary = "units/conversions Gem"
13
+ gemspec.description = %{A simple way to add units and conversion ability to numbers in Ruby}
14
+ # gemspec.files = Dir['lib/**/*.rb'] + Dir['test/**/*.rb'] + ["LICENSE", 'README', 'Rakefile']
15
+ # gemspec.require_path = 'lib'
16
+ # gemspec.has_rdoc = false
17
+ gemspec.author = "Lucas Carlson"
18
+ gemspec.email = "lucas@rufy.com"
19
+ gemspec.homepage = "http://rubyforge.org/projects/units"
20
+ end
21
+ rescue LoadError
22
+ puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
23
+ end
24
+
25
+ desc "Default Task"
26
+ task :default => [ :test ]
27
+
28
+ # Run the unit tests
29
+ desc "Run all unit tests"
30
+ Rake::TestTask.new("test") { |t|
31
+ t.libs << "lib"
32
+ t.pattern = 'test/*/*_test.rb'
33
+ t.verbose = true
34
+ }
35
+
36
+ # Make a console, useful when working on tests
37
+ desc "Generate a test console"
38
+ task :console do
39
+ verbose( false ) { sh "irb -I lib/ -r 'units/standard' -r 'units/currency'" }
40
+ end
41
+
42
+ # Genereate the RDoc documentation
43
+ desc "Create documentation"
44
+ Rake::RDocTask.new("doc") { |rdoc|
45
+ rdoc.title = "Ruby Units"
46
+ rdoc.rdoc_dir = 'html'
47
+ rdoc.rdoc_files.include('README')
48
+ rdoc.rdoc_files.include('LICENSE')
49
+ rdoc.rdoc_files.include('lib/**/*.rb')
50
+ }
51
+
52
+ desc "Report code statistics (KLOCs, etc) from the application"
53
+ task :stats do
54
+ require 'code_statistics'
55
+ CodeStatistics.new(
56
+ ["Library", "lib"],
57
+ ["Units", "test"]
58
+ ).to_s
59
+ end
60
+
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.0.3
data/lib/units/base.rb ADDED
@@ -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
+ elsif self.class.unit_aliases[kind]
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,167 @@
1
+ require 'units/base'
2
+
3
+ class Numeric
4
+ WEIGHT = {
5
+ :kilograms => 1.0,
6
+ :pounds => 0.45359237,
7
+ :ounces => 0.028349523125,
8
+ :grams => 0.001
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
+ :pints => 0.125,
18
+ :milliliters => 0.000264172051,
19
+ :cubic_feet => 7.48051945,
20
+ :cups => 0.0625,
21
+ :microliters => 2.64172051,
22
+ :cubic_inches => 0.00432900431,
23
+ :liters => 0.264172051,
24
+ :cubic_centimeters => 0.000264172051,
25
+ :cubic_yards => 201.974025,
26
+ :hectoliters => 26.4172051,
27
+ :fluid_ounces => 0.0078125,
28
+ :cubic_millimeters => 2.64172051,
29
+ :gallons => 1,
30
+ :deciliters => 0.0264172051,
31
+ :tablespoons => 0.00390625,
32
+ :cubic_meters => 264.172051,
33
+ :quarts => 0.25,
34
+ :centiliters => 0.00264172051,
35
+ :teaspoons => 0.00130208333,
36
+ :cubic_decimeters => 0.264172051
37
+ }
38
+ VOLUME_ALIASES = {
39
+ :liters => [ :liter, :l ],
40
+ :hectoliters => [ :hectoliter, :hl ],
41
+ :deciliters => [ :deciliter, :dl ],
42
+ :centiliters => [ :centiliter, :cl ],
43
+ :milliliters => [ :milliliter, :ml ],
44
+ :microliters => [ :microliter, :ul ],
45
+ :cubic_centimeters => [ :cubic_centimeter, :cm3 ],
46
+ :cubic_millimeters => [ :cubic_millimeter, :mm3 ],
47
+ :cubic_meters => [ :cubic_meter, :m3 ],
48
+ :cubic_decimeters => [ :cubic_decimeter, :dm3 ],
49
+ :cubic_feet => [ :cubic_foot, :f3 ],
50
+ :cubic_inches => [ :cubic_inch, :i3 ],
51
+ :cubic_yards => [ :cubic_yard, :y3 ],
52
+ :gallons => [ :gallon, :gal, :gals ],
53
+ :quarts => [ :quart, :qt, :qts ],
54
+ :pints => [ :pint, :pt, :pts ],
55
+ :cups => [ :cup ],
56
+ :gills => [ :gill ],
57
+ :fluid_ounces => [ :fluid_oz, :fluid_ozs ],
58
+ :tablespoons => [ :tablespoon, :tbsp ],
59
+ :teaspoons => [ :teaspoon, :tsp ],
60
+ :fluid_drams => [ :fluid_dram ],
61
+ :minims => [ :minim ]
62
+ }
63
+ TIME = {
64
+ :seconds => 1.0,
65
+ :minutes => 60.0,
66
+ :hours => 3600.0,
67
+ :days => 86400.0,
68
+ :weeks => 604800.0,
69
+ :years => 31449600.0
70
+ }
71
+ TIME_ALIASES = {
72
+ :seconds => [ :sec, :second ],
73
+ :minutes => [ :min, :mins, :minute ],
74
+ :hours => [ :hour ],
75
+ :days => [ :day ],
76
+ :weeks => [ :week ],
77
+ :years => [ :year ]
78
+ }
79
+ SIZE = {
80
+ :bytes => 1.0,
81
+ :bits => 8.0,
82
+ :kilobytes => 1024.0,
83
+ :megabytes => 1048576.0,
84
+ :gigabytes => 1073741824.0,
85
+ :terabytes => 1099511627776.0,
86
+ :petabytes => 1.12589991e15
87
+ }
88
+ SIZE_ALIASES = {
89
+ :bits => [ :bit ],
90
+ :bytes => [ :b, :byte ],
91
+ :kilobytes => [ :kb, :kilobyte ],
92
+ :megabytes => [ :mb, :megabyte ],
93
+ :gigabytes => [ :gb, :gigabyte ],
94
+ :terabytes => [ :tb, :terabyte ],
95
+ :petabytes => [ :pb, :petabyte ]
96
+ }
97
+ LENGTH = {
98
+ :inches => 1.0,
99
+ :feet => 12.0,
100
+ :meters => 39.3700787,
101
+ :kilometers => 39370.0787,
102
+ :milimeters => 0.0393700787,
103
+ :centimeters => 0.393700787,
104
+ :miles => 63360.0
105
+ }
106
+ LENGTH_ALIASES = {
107
+ :inches => [ :inch ],
108
+ :feet => [ :foot ],
109
+ :miles => [ :mile ],
110
+ :meters => [ :m, :meter ],
111
+ :kilometers => [ :km, :kilometer ],
112
+ :milimeters => [ :mm, :milimeter ],
113
+ :centimeters => [ :cm, :centimeter ]
114
+ }
115
+ SPEED = {
116
+ :kph => 1.0,
117
+ :mph => 1.609344
118
+ }
119
+ SPEED_ALIASES = {
120
+ :mph => [ :miles_per_hour ],
121
+ :kph => [ :kilometers_per_hour ]
122
+ }
123
+ add_unit_conversions(
124
+ :weight => WEIGHT,
125
+ :volume => VOLUME,
126
+ :time => TIME,
127
+ :size => SIZE,
128
+ :length => LENGTH,
129
+ :speed => SPEED
130
+ )
131
+
132
+ add_unit_aliases(
133
+ :weight => WEIGHT_ALIASES,
134
+ :volume => VOLUME_ALIASES,
135
+ :time => TIME_ALIASES,
136
+ :size => SIZE_ALIASES,
137
+ :length => LENGTH_ALIASES,
138
+ :speed => SPEED_ALIASES
139
+ )
140
+
141
+ end
142
+
143
+ class Float #:nodoc:
144
+ alias :_to_i :to_i
145
+ def to_i
146
+ case kind
147
+ when :time
148
+ to_seconds._to_i
149
+ when :size
150
+ to_bytes._to_i
151
+ else
152
+ _to_i
153
+ end
154
+ end
155
+
156
+ alias :_to_int :to_int
157
+ def to_int
158
+ case kind
159
+ when :time
160
+ to_seconds._to_int
161
+ when :size
162
+ to_bytes._to_int
163
+ else
164
+ _to_int
165
+ end
166
+ end
167
+ end
data/lib/units.rb ADDED
@@ -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,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,25 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+ begin
3
+ require 'units/currency'
4
+ rescue => e
5
+ # probably had a problem loading the dynamic currency thing
6
+ $failed_currency_loading = true
7
+ end
8
+
9
+ class CurrencyTest < Test::Unit::TestCase
10
+ if $failed_currency_loading
11
+ def test_euro_to_dollar
12
+ raise "Failed to load units/currency"
13
+ end
14
+ else
15
+
16
+ def test_euro_to_dollar
17
+ assert_equal Hash.new, Numeric.currency_rates
18
+
19
+ assert_in_delta 1.5, 1.euro.usd, 0.5
20
+ assert Numeric.currency_rates[:euro_to_euro] == 1.0
21
+ assert_equal 2, Numeric.currency_rates.size
22
+ end
23
+
24
+ end
25
+ end
@@ -0,0 +1,74 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class StandardTest < Test::Unit::TestCase
4
+ def test_to_i
5
+ assert_equal 10, 10.0.to_i
6
+ end
7
+
8
+ def test_to_int
9
+ assert_equal 10, 10.0.to_int
10
+ end
11
+
12
+ def test_pounds_to_ounces
13
+ ounces = 4.pounds.to_ounces
14
+ assert_equal 64.0, ounces
15
+ assert_equal :ounces, ounces.units
16
+ assert_equal :weight, ounces.kind
17
+ end
18
+
19
+ def test_pounds_to_kilograms
20
+ kilograms = 1.lb.to_kg
21
+ assert_equal 0.45359237, kilograms
22
+ assert_equal :kilograms, kilograms.units
23
+ assert_equal :weight, kilograms.kind
24
+ end
25
+
26
+ # For some reason this test fails when comparing floats to one another
27
+ def test_kilograms_to_pounds
28
+ pounds = 1.kg.to_lb
29
+ assert_equal "2.20462262184878", pounds.to_s
30
+ assert_equal :pounds, pounds.units
31
+ assert_equal :weight, pounds.kind
32
+ end
33
+
34
+ def test_cups_to_quarts
35
+ quarts = 1.cup.to_quarts
36
+ assert_equal 0.25, quarts
37
+ assert_equal :quarts, quarts.units
38
+ assert_equal :volume, quarts.kind
39
+ end
40
+
41
+ def test_quarts_to_cups
42
+ cups = 4.quarts.to_cups
43
+ assert_equal 16.0, cups
44
+ assert_equal :cups, cups.units
45
+ assert_equal :volume, cups.kind
46
+ end
47
+
48
+ def test_minutes_to_seconds
49
+ seconds = 1.minute.to_seconds
50
+ assert_equal 60.0, seconds
51
+ assert_equal :seconds, seconds.unit
52
+ assert_equal :time, seconds.kind
53
+ end
54
+
55
+ def test_megabytes_to_kilobytes
56
+ kilobytes = 1.mb.to_kb
57
+ assert_equal 1024.0, kilobytes
58
+ assert_equal :kilobytes, kilobytes.units
59
+ assert_equal :size, kilobytes.kind
60
+ end
61
+
62
+ def test_length
63
+ centimeters = 1.inch.to_cm
64
+ assert_equal 2.5400000025908, centimeters
65
+ assert_equal :centimeters, centimeters.units
66
+ assert_equal :length, centimeters.kind
67
+ end
68
+
69
+ def test_speed
70
+ assert_equal 1.609344, 1.mph.to_kph
71
+ assert_equal 1, 1.609344.kph.to_mph
72
+ assert_equal :speed, (1.mph.to_kph).kind
73
+ end
74
+ end
data/units.gemspec ADDED
@@ -0,0 +1,53 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ Gem::Specification.new do |s|
4
+ s.name = %q{units}
5
+ s.version = "1.0.3"
6
+
7
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
8
+ s.authors = ["Lucas Carlson"]
9
+ s.date = %q{2009-07-30}
10
+ s.description = %q{A simple way to add units and conversion ability to numbers in Ruby}
11
+ s.email = %q{lucas@rufy.com}
12
+ s.extra_rdoc_files = [
13
+ "LICENSE",
14
+ "README"
15
+ ]
16
+ s.files = [
17
+ "LICENSE",
18
+ "README",
19
+ "Rakefile",
20
+ "VERSION",
21
+ "lib/units.rb",
22
+ "lib/units/base.rb",
23
+ "lib/units/currency.rb",
24
+ "lib/units/standard.rb",
25
+ "test/test_helper.rb",
26
+ "test/units/base_test.rb",
27
+ "test/units/currency_test.rb",
28
+ "test/units/standard_test.rb",
29
+ "units.gemspec"
30
+ ]
31
+ s.has_rdoc = true
32
+ s.homepage = %q{http://rubyforge.org/projects/units}
33
+ s.rdoc_options = ["--charset=UTF-8"]
34
+ s.require_paths = ["lib"]
35
+ s.rubygems_version = %q{1.3.1}
36
+ s.summary = %q{units/conversions Gem}
37
+ s.test_files = [
38
+ "test/test_helper.rb",
39
+ "test/units/base_test.rb",
40
+ "test/units/currency_test.rb",
41
+ "test/units/standard_test.rb"
42
+ ]
43
+
44
+ if s.respond_to? :specification_version then
45
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
46
+ s.specification_version = 2
47
+
48
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
49
+ else
50
+ end
51
+ else
52
+ end
53
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: woahdae-units
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.2
4
+ version: 1.0.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Lucas Carlson
@@ -9,7 +9,7 @@ autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
11
 
12
- date: 2009-05-16 00:00:00 -07:00
12
+ date: 2009-07-30 00:00:00 -07:00
13
13
  default_executable:
14
14
  dependencies: []
15
15
 
@@ -19,16 +19,29 @@ executables: []
19
19
 
20
20
  extensions: []
21
21
 
22
- extra_rdoc_files: []
23
-
24
- files: []
25
-
26
- has_rdoc: false
22
+ extra_rdoc_files:
23
+ - LICENSE
24
+ - README
25
+ files:
26
+ - LICENSE
27
+ - README
28
+ - Rakefile
29
+ - VERSION
30
+ - lib/units.rb
31
+ - lib/units/base.rb
32
+ - lib/units/currency.rb
33
+ - lib/units/standard.rb
34
+ - test/test_helper.rb
35
+ - test/units/base_test.rb
36
+ - test/units/currency_test.rb
37
+ - test/units/standard_test.rb
38
+ - units.gemspec
39
+ has_rdoc: true
27
40
  homepage: http://rubyforge.org/projects/units
28
41
  licenses:
29
42
  post_install_message:
30
- rdoc_options: []
31
-
43
+ rdoc_options:
44
+ - --charset=UTF-8
32
45
  require_paths:
33
46
  - lib
34
47
  required_ruby_version: !ruby/object:Gem::Requirement
@@ -50,5 +63,8 @@ rubygems_version: 1.3.5
50
63
  signing_key:
51
64
  specification_version: 2
52
65
  summary: units/conversions Gem
53
- test_files: []
54
-
66
+ test_files:
67
+ - test/test_helper.rb
68
+ - test/units/base_test.rb
69
+ - test/units/currency_test.rb
70
+ - test/units/standard_test.rb