repo
string
commit
string
message
string
diff
string
infused/stater
cabf8b1ed7eedf47c4b8d66c07c53f8dcc5345e9
Cleanup
diff --git a/lib/stater/amortization.rb b/lib/stater/amortization.rb index 0752df0..1d840e3 100644 --- a/lib/stater/amortization.rb +++ b/lib/stater/amortization.rb @@ -1,52 +1,52 @@ -Struct.new('Payment', :payment_number, :payment, :principal, :interest, :principal_balance) +Struct.new('Payment', :number, :payment, :principal_paid, :interest_paid, :principal_balance) class NilClass def to_d nil end end # TODO: test that this actually works # BigDecimal.mode(BigDecimal::ROUND_HALF_EVEN) module Stater class Amortization attr_accessor :principal attr_accessor :periodic_rate attr_accessor :periods def initialize(principal = nil, periodic_rate = nil, periods = nil) @schedule = [] @principal, @periodic_rate, @periods = principal.to_d, periodic_rate.to_d, periods end # Calculates the payment when given the principal amount and interest rate - def calculate_payment - x = @periodic_rate * @principal * ((1 + @periodic_rate)**@periods) - y = ((1 + @periodic_rate)**@periods) - 1 - result = x / y + def calculate_payment(periodic_rate = @periodic_rate, periods = @periods) + raise ArgumentError, "periodic_rate should be a BigDecimal" unless periodic_rate.is_a?(BigDecimal) + raise ArgumentError, "periods should be a Fixnum" unless periods.is_a?(Fixnum) - BigDecimal(result.to_s).round(2) #.to_f + x = periodic_rate * principal * ((1 + periodic_rate)**periods) + y = ((1 + periodic_rate)**periods) - 1 + (x / y).round(2) end def schedule return [] if @principal.nil? or @periodic_rate.nil? or @periods.nil? payments = [] - pmt = calculate_payment + payment = calculate_payment principal_balance = @principal - # p "payment, principal, interest, balance" + 1.upto(@periods) do |payment_number| interest_paid = (principal_balance * @periodic_rate).round(2) - principal = pmt - interest_paid - principal_balance = principal_balance - principal + principal_paid = payment - interest_paid + principal_balance = principal_balance - principal_paid - # p "#{pmt.to_s('F')}, #{principal.to_s('F')}, #{interest_paid.to_s('F')}, #{principal_balance.to_s('F')}" - payments << Struct::Payment.new(payment_number, pmt, principal.round(2), interest_paid, principal_balance.round(2)) + payments << Struct::Payment.new(payment_number, payment, principal_paid, interest_paid, principal_balance) end payments end end end \ No newline at end of file diff --git a/test/test_helper.rb b/test/test_helper.rb index c72076a..a1ac9d5 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,37 +1,37 @@ $:.unshift(File.dirname(__FILE__) + "/../lib/") require 'test/unit' require 'stater' require 'rubygems' require 'hpricot' class Test::Unit::TestCase def assert_schedule(xml_file, schedule) control_schedule = [] doc = Hpricot(open(xml_file)) lines = (doc/:tvalueamortizationschedule/:amortizationline) lines.each do |line| if line.search(:amortizationlinetype).innerHTML == '9' payment = line.search(:payment1amount).innerHTML.gsub(/(\d{2})\d{2}$/, '.\1') interest_paid = line.search(:interestpaid).innerHTML.gsub(/(\d{2})\d{2}$/, '.\1') principal_paid = line.search(:principalpaid).innerHTML.gsub(/(\d{2})\d{2}$/, '.\1') principal_balance = line.search(:principalbalance).innerHTML.gsub(/(\d{2})\d{2}$/, '.\1') control_schedule << Struct::Payment.new(nil, payment, principal_paid, interest_paid, principal_balance) end end # assert_equal control_schedule.size, schedule.size, "The number of amortization lines is not the same." schedule.each_with_index do |line, index| assert_equal control_schedule[index].payment, line.payment.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), "payment at amortization line: #{index}" - assert_equal control_schedule[index].interest, line.interest.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), + assert_equal control_schedule[index].interest_paid, line.interest_paid.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), "interest at amortization line #{index}" - assert_equal control_schedule[index].principal, line.principal.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), + assert_equal control_schedule[index].principal_paid, line.principal_paid.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), "principal at amortization line #{index}" assert_equal control_schedule[index].principal_balance, line.principal_balance.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), "principal_balance at amortization line #{index}" end end end
infused/stater
380f6d41472b516021dc309d8af37b8d8355d176
Amortizations are now matching the output from TValue
diff --git a/lib/stater/amortization.rb b/lib/stater/amortization.rb index f0a19e6..0752df0 100644 --- a/lib/stater/amortization.rb +++ b/lib/stater/amortization.rb @@ -1,50 +1,52 @@ -Struct.new('Payment', :payment_number, :payment, :principal, :interest, :remaining_principal) +Struct.new('Payment', :payment_number, :payment, :principal, :interest, :principal_balance) + class NilClass def to_d nil end end +# TODO: test that this actually works +# BigDecimal.mode(BigDecimal::ROUND_HALF_EVEN) + module Stater class Amortization attr_accessor :principal attr_accessor :periodic_rate attr_accessor :periods def initialize(principal = nil, periodic_rate = nil, periods = nil) @schedule = [] @principal, @periodic_rate, @periods = principal.to_d, periodic_rate.to_d, periods end # Calculates the payment when given the principal amount and interest rate - def payment + def calculate_payment x = @periodic_rate * @principal * ((1 + @periodic_rate)**@periods) y = ((1 + @periodic_rate)**@periods) - 1 result = x / y BigDecimal(result.to_s).round(2) #.to_f end def schedule - # return [] if @principal.nil? or @period_rate.nil? or @periods.nil? + return [] if @principal.nil? or @periodic_rate.nil? or @periods.nil? payments = [] - pmt = payment - remaining_principal = @principal - payment_number = 0 - while remaining_principal > 0 do - payment_number += 1 + pmt = calculate_payment + principal_balance = @principal + # p "payment, principal, interest, balance" + 1.upto(@periods) do |payment_number| + interest_paid = (principal_balance * @periodic_rate).round(2) + principal = pmt - interest_paid + principal_balance = principal_balance - principal - interest = remaining_principal * @periodic_rate - principal = pmt - interest - remaining_principal = remaining_principal - principal - - payments << Struct::Payment.new(payment_number, pmt, principal, interest, remaining_principal) + # p "#{pmt.to_s('F')}, #{principal.to_s('F')}, #{interest_paid.to_s('F')}, #{principal_balance.to_s('F')}" + payments << Struct::Payment.new(payment_number, pmt, principal.round(2), interest_paid, principal_balance.round(2)) end payments end - end end \ No newline at end of file diff --git a/test/fixtures/FEC_example_3_3_1.csv b/test/fixtures/FEC_example_3_3_1.csv index ab18642..493f409 100644 --- a/test/fixtures/FEC_example_3_3_1.csv +++ b/test/fixtures/FEC_example_3_3_1.csv @@ -1,234 +1,235 @@ "Test1" Compound Period: Monthly Nominal Annual Rate: 8.000 % CASH FLOW DATA Event Date Amount Number Period End Date 1 Loan 05/08/2007 "250,000.00" 1 2 Payment 06/08/2007 "2,389.13" 180 Monthly 05/08/2022 +3 Payment 06/08/2022 "0.11" 1 AMORTIZATION SCHEDULE - Normal Amortization # Date Payment Interest Principal Balance Loan 05/08/2007 "250,000.00" 1 06/08/2007 "2,389.13" "1,666.67" "722.46" "249,277.54" 2 07/08/2007 "2,389.13" "1,661.85" "727.28" "248,550.26" 3 08/08/2007 "2,389.13" "1,657.00" "732.13" "247,818.13" 4 09/08/2007 "2,389.13" "1,652.12" "737.01" "247,081.12" 5 10/08/2007 "2,389.13" "1,647.21" "741.92" "246,339.20" 6 11/08/2007 "2,389.13" "1,642.26" "746.87" "245,592.33" 7 12/08/2007 "2,389.13" "1,637.28" "751.85" "244,840.48" 2007 Totals "16,723.91" "11,564.39" "5,159.52" 8 01/08/2008 "2,389.13" "1,632.27" "756.86" "244,083.62" 9 02/08/2008 "2,389.13" "1,627.22" "761.91" "243,321.71" 10 03/08/2008 "2,389.13" "1,622.14" "766.99" "242,554.72" 11 04/08/2008 "2,389.13" "1,617.03" "772.10" "241,782.62" 12 05/08/2008 "2,389.13" "1,611.88" "777.25" "241,005.37" 13 06/08/2008 "2,389.13" "1,606.70" "782.43" "240,222.94" 14 07/08/2008 "2,389.13" "1,601.49" "787.64" "239,435.30" 15 08/08/2008 "2,389.13" "1,596.24" "792.89" "238,642.41" 16 09/08/2008 "2,389.13" "1,590.95" "798.18" "237,844.23" 17 10/08/2008 "2,389.13" "1,585.63" "803.50" "237,040.73" 18 11/08/2008 "2,389.13" "1,580.27" "808.86" "236,231.87" 19 12/08/2008 "2,389.13" "1,574.88" "814.25" "235,417.62" 2008 Totals "28,669.56" "19,246.70" "9,422.86" 20 01/08/2009 "2,389.13" "1,569.45" "819.68" "234,597.94" 21 02/08/2009 "2,389.13" "1,563.99" "825.14" "233,772.80" 22 03/08/2009 "2,389.13" "1,558.49" "830.64" "232,942.16" 23 04/08/2009 "2,389.13" "1,552.95" "836.18" "232,105.98" 24 05/08/2009 "2,389.13" "1,547.37" "841.76" "231,264.22" 25 06/08/2009 "2,389.13" "1,541.76" "847.37" "230,416.85" 26 07/08/2009 "2,389.13" "1,536.11" "853.02" "229,563.83" 27 08/08/2009 "2,389.13" "1,530.43" "858.70" "228,705.13" 28 09/08/2009 "2,389.13" "1,524.70" "864.43" "227,840.70" 29 10/08/2009 "2,389.13" "1,518.94" "870.19" "226,970.51" 30 11/08/2009 "2,389.13" "1,513.14" "875.99" "226,094.52" 31 12/08/2009 "2,389.13" "1,507.30" "881.83" "225,212.69" 2009 Totals "28,669.56" "18,464.63" "10,204.93" 32 01/08/2010 "2,389.13" "1,501.42" "887.71" "224,324.98" 33 02/08/2010 "2,389.13" "1,495.50" "893.63" "223,431.35" 34 03/08/2010 "2,389.13" "1,489.54" "899.59" "222,531.76" 35 04/08/2010 "2,389.13" "1,483.55" "905.58" "221,626.18" 36 05/08/2010 "2,389.13" "1,477.51" "911.62" "220,714.56" 37 06/08/2010 "2,389.13" "1,471.43" "917.70" "219,796.86" 38 07/08/2010 "2,389.13" "1,465.31" "923.82" "218,873.04" 39 08/08/2010 "2,389.13" "1,459.15" "929.98" "217,943.06" 40 09/08/2010 "2,389.13" "1,452.95" "936.18" "217,006.88" 41 10/08/2010 "2,389.13" "1,446.71" "942.42" "216,064.46" 42 11/08/2010 "2,389.13" "1,440.43" "948.70" "215,115.76" 43 12/08/2010 "2,389.13" "1,434.11" "955.02" "214,160.74" 2010 Totals "28,669.56" "17,617.61" "11,051.95" 44 01/08/2011 "2,389.13" "1,427.74" "961.39" "213,199.35" 45 02/08/2011 "2,389.13" "1,421.33" "967.80" "212,231.55" 46 03/08/2011 "2,389.13" "1,414.88" "974.25" "211,257.30" 47 04/08/2011 "2,389.13" "1,408.38" "980.75" "210,276.55" 48 05/08/2011 "2,389.13" "1,401.84" "987.29" "209,289.26" 49 06/08/2011 "2,389.13" "1,395.26" "993.87" "208,295.39" 50 07/08/2011 "2,389.13" "1,388.64" "1,000.49" "207,294.90" 51 08/08/2011 "2,389.13" "1,381.97" "1,007.16" "206,287.74" 52 09/08/2011 "2,389.13" "1,375.25" "1,013.88" "205,273.86" 53 10/08/2011 "2,389.13" "1,368.49" "1,020.64" "204,253.22" 54 11/08/2011 "2,389.13" "1,361.69" "1,027.44" "203,225.78" 55 12/08/2011 "2,389.13" "1,354.84" "1,034.29" "202,191.49" 2011 Totals "28,669.56" "16,700.31" "11,969.25" 56 01/08/2012 "2,389.13" "1,347.94" "1,041.19" "201,150.30" 57 02/08/2012 "2,389.13" "1,341.00" "1,048.13" "200,102.17" 58 03/08/2012 "2,389.13" "1,334.01" "1,055.12" "199,047.05" 59 04/08/2012 "2,389.13" "1,326.98" "1,062.15" "197,984.90" 60 05/08/2012 "2,389.13" "1,319.90" "1,069.23" "196,915.67" 61 06/08/2012 "2,389.13" "1,312.77" "1,076.36" "195,839.31" 62 07/08/2012 "2,389.13" "1,305.60" "1,083.53" "194,755.78" 63 08/08/2012 "2,389.13" "1,298.37" "1,090.76" "193,665.02" 64 09/08/2012 "2,389.13" "1,291.10" "1,098.03" "192,566.99" 65 10/08/2012 "2,389.13" "1,283.78" "1,105.35" "191,461.64" 66 11/08/2012 "2,389.13" "1,276.41" "1,112.72" "190,348.92" 67 12/08/2012 "2,389.13" "1,268.99" "1,120.14" "189,228.78" 2012 Totals "28,669.56" "15,706.85" "12,962.71" 68 01/08/2013 "2,389.13" "1,261.53" "1,127.60" "188,101.18" 69 02/08/2013 "2,389.13" "1,254.01" "1,135.12" "186,966.06" 70 03/08/2013 "2,389.13" "1,246.44" "1,142.69" "185,823.37" 71 04/08/2013 "2,389.13" "1,238.82" "1,150.31" "184,673.06" 72 05/08/2013 "2,389.13" "1,231.15" "1,157.98" "183,515.08" 73 06/08/2013 "2,389.13" "1,223.43" "1,165.70" "182,349.38" 74 07/08/2013 "2,389.13" "1,215.66" "1,173.47" "181,175.91" 75 08/08/2013 "2,389.13" "1,207.84" "1,181.29" "179,994.62" 76 09/08/2013 "2,389.13" "1,199.96" "1,189.17" "178,805.45" 77 10/08/2013 "2,389.13" "1,192.04" "1,197.09" "177,608.36" 78 11/08/2013 "2,389.13" "1,184.06" "1,205.07" "176,403.29" 79 12/08/2013 "2,389.13" "1,176.02" "1,213.11" "175,190.18" 2013 Totals "28,669.56" "14,630.96" "14,038.60" 80 01/08/2014 "2,389.13" "1,167.93" "1,221.20" "173,968.98" 81 02/08/2014 "2,389.13" "1,159.79" "1,229.34" "172,739.64" 82 03/08/2014 "2,389.13" "1,151.60" "1,237.53" "171,502.11" 83 04/08/2014 "2,389.13" "1,143.35" "1,245.78" "170,256.33" 84 05/08/2014 "2,389.13" "1,135.04" "1,254.09" "169,002.24" 85 06/08/2014 "2,389.13" "1,126.68" "1,262.45" "167,739.79" 86 07/08/2014 "2,389.13" "1,118.27" "1,270.86" "166,468.93" 87 08/08/2014 "2,389.13" "1,109.79" "1,279.34" "165,189.59" 88 09/08/2014 "2,389.13" "1,101.26" "1,287.87" "163,901.72" 89 10/08/2014 "2,389.13" "1,092.68" "1,296.45" "162,605.27" 90 11/08/2014 "2,389.13" "1,084.04" "1,305.09" "161,300.18" 91 12/08/2014 "2,389.13" "1,075.33" "1,313.80" "159,986.38" 2014 Totals "28,669.56" "13,465.76" "15,203.80" 92 01/08/2015 "2,389.13" "1,066.58" "1,322.55" "158,663.83" 93 02/08/2015 "2,389.13" "1,057.76" "1,331.37" "157,332.46" 94 03/08/2015 "2,389.13" "1,048.88" "1,340.25" "155,992.21" 95 04/08/2015 "2,389.13" "1,039.95" "1,349.18" "154,643.03" 96 05/08/2015 "2,389.13" "1,030.95" "1,358.18" "153,284.85" 97 06/08/2015 "2,389.13" "1,021.90" "1,367.23" "151,917.62" 98 07/08/2015 "2,389.13" "1,012.78" "1,376.35" "150,541.27" 99 08/08/2015 "2,389.13" "1,003.61" "1,385.52" "149,155.75" 100 09/08/2015 "2,389.13" "994.37" "1,394.76" "147,760.99" 101 10/08/2015 "2,389.13" "985.07" "1,404.06" "146,356.93" 102 11/08/2015 "2,389.13" "975.71" "1,413.42" "144,943.51" 103 12/08/2015 "2,389.13" "966.29" "1,422.84" "143,520.67" 2015 Totals "28,669.56" "12,203.85" "16,465.71" 104 01/08/2016 "2,389.13" "956.80" "1,432.33" "142,088.34" 105 02/08/2016 "2,389.13" "947.26" "1,441.87" "140,646.47" 106 03/08/2016 "2,389.13" "937.64" "1,451.49" "139,194.98" 107 04/08/2016 "2,389.13" "927.97" "1,461.16" "137,733.82" 108 05/08/2016 "2,389.13" "918.23" "1,470.90" "136,262.92" 109 06/08/2016 "2,389.13" "908.42" "1,480.71" "134,782.21" 110 07/08/2016 "2,389.13" "898.55" "1,490.58" "133,291.63" 111 08/08/2016 "2,389.13" "888.61" "1,500.52" "131,791.11" 112 09/08/2016 "2,389.13" "878.61" "1,510.52" "130,280.59" 113 10/08/2016 "2,389.13" "868.54" "1,520.59" "128,760.00" 114 11/08/2016 "2,389.13" "858.40" "1,530.73" "127,229.27" 115 12/08/2016 "2,389.13" "848.20" "1,540.93" "125,688.34" 2016 Totals "28,669.56" "10,837.23" "17,832.33" 116 01/08/2017 "2,389.13" "837.92" "1,551.21" "124,137.13" 117 02/08/2017 "2,389.13" "827.58" "1,561.55" "122,575.58" 118 03/08/2017 "2,389.13" "817.17" "1,571.96" "121,003.62" 119 04/08/2017 "2,389.13" "806.69" "1,582.44" "119,421.18" 120 05/08/2017 "2,389.13" "796.14" "1,592.99" "117,828.19" 121 06/08/2017 "2,389.13" "785.52" "1,603.61" "116,224.58" 122 07/08/2017 "2,389.13" "774.83" "1,614.30" "114,610.28" 123 08/08/2017 "2,389.13" "764.07" "1,625.06" "112,985.22" 124 09/08/2017 "2,389.13" "753.23" "1,635.90" "111,349.32" 125 10/08/2017 "2,389.13" "742.33" "1,646.80" "109,702.52" 126 11/08/2017 "2,389.13" "731.35" "1,657.78" "108,044.74" 127 12/08/2017 "2,389.13" "720.30" "1,668.83" "106,375.91" 2017 Totals "28,669.56" "9,357.13" "19,312.43" 128 01/08/2018 "2,389.13" "709.17" "1,679.96" "104,695.95" 129 02/08/2018 "2,389.13" "697.97" "1,691.16" "103,004.79" 130 03/08/2018 "2,389.13" "686.70" "1,702.43" "101,302.36" 131 04/08/2018 "2,389.13" "675.35" "1,713.78" "99,588.58" 132 05/08/2018 "2,389.13" "663.92" "1,725.21" "97,863.37" 133 06/08/2018 "2,389.13" "652.42" "1,736.71" "96,126.66" 134 07/08/2018 "2,389.13" "640.84" "1,748.29" "94,378.37" 135 08/08/2018 "2,389.13" "629.19" "1,759.94" "92,618.43" 136 09/08/2018 "2,389.13" "617.46" "1,771.67" "90,846.76" 137 10/08/2018 "2,389.13" "605.65" "1,783.48" "89,063.28" 138 11/08/2018 "2,389.13" "593.76" "1,795.37" "87,267.91" 139 12/08/2018 "2,389.13" "581.79" "1,807.34" "85,460.57" 2018 Totals "28,669.56" "7,754.22" "20,915.34" 140 01/08/2019 "2,389.13" "569.74" "1,819.39" "83,641.18" 141 02/08/2019 "2,389.13" "557.61" "1,831.52" "81,809.66" 142 03/08/2019 "2,389.13" "545.40" "1,843.73" "79,965.93" 143 04/08/2019 "2,389.13" "533.11" "1,856.02" "78,109.91" 144 05/08/2019 "2,389.13" "520.73" "1,868.40" "76,241.51" 145 06/08/2019 "2,389.13" "508.28" "1,880.85" "74,360.66" 146 07/08/2019 "2,389.13" "495.74" "1,893.39" "72,467.27" 147 08/08/2019 "2,389.13" "483.12" "1,906.01" "70,561.26" 148 09/08/2019 "2,389.13" "470.41" "1,918.72" "68,642.54" 149 10/08/2019 "2,389.13" "457.62" "1,931.51" "66,711.03" 150 11/08/2019 "2,389.13" "444.74" "1,944.39" "64,766.64" 151 12/08/2019 "2,389.13" "431.78" "1,957.35" "62,809.29" 2019 Totals "28,669.56" "6,018.28" "22,651.28" 152 01/08/2020 "2,389.13" "418.73" "1,970.40" "60,838.89" 153 02/08/2020 "2,389.13" "405.59" "1,983.54" "58,855.35" 154 03/08/2020 "2,389.13" "392.37" "1,996.76" "56,858.59" 155 04/08/2020 "2,389.13" "379.06" "2,010.07" "54,848.52" 156 05/08/2020 "2,389.13" "365.66" "2,023.47" "52,825.05" 157 06/08/2020 "2,389.13" "352.17" "2,036.96" "50,788.09" 158 07/08/2020 "2,389.13" "338.59" "2,050.54" "48,737.55" 159 08/08/2020 "2,389.13" "324.92" "2,064.21" "46,673.34" 160 09/08/2020 "2,389.13" "311.16" "2,077.97" "44,595.37" 161 10/08/2020 "2,389.13" "297.30" "2,091.83" "42,503.54" 162 11/08/2020 "2,389.13" "283.36" "2,105.77" "40,397.77" 163 12/08/2020 "2,389.13" "269.32" "2,119.81" "38,277.96" 2020 Totals "28,669.56" "4,138.23" "24,531.33" 164 01/08/2021 "2,389.13" "255.19" "2,133.94" "36,144.02" 165 02/08/2021 "2,389.13" "240.96" "2,148.17" "33,995.85" 166 03/08/2021 "2,389.13" "226.64" "2,162.49" "31,833.36" 167 04/08/2021 "2,389.13" "212.22" "2,176.91" "29,656.45" 168 05/08/2021 "2,389.13" "197.71" "2,191.42" "27,465.03" 169 06/08/2021 "2,389.13" "183.10" "2,206.03" "25,259.00" 170 07/08/2021 "2,389.13" "168.39" "2,220.74" "23,038.26" 171 08/08/2021 "2,389.13" "153.59" "2,235.54" "20,802.72" 172 09/08/2021 "2,389.13" "138.68" "2,250.45" "18,552.27" 173 10/08/2021 "2,389.13" "123.68" "2,265.45" "16,286.82" 174 11/08/2021 "2,389.13" "108.58" "2,280.55" "14,006.27" 175 12/08/2021 "2,389.13" "93.38" "2,295.75" "11,710.52" 2021 Totals "28,669.56" "2,102.12" "26,567.44" 176 01/08/2022 "2,389.13" "78.07" "2,311.06" "9,399.46" 177 02/08/2022 "2,389.13" "62.66" "2,326.47" "7,072.99" 178 03/08/2022 "2,389.13" "47.15" "2,341.98" "4,731.01" 179 04/08/2022 "2,389.13" "31.54" "2,357.59" "2,373.42" -180 05/08/2022 "2,389.13" "15.71" "2,373.42" "0.00" -2022 Totals "11,945.65" "235.13" "11,710.52" +180 05/08/2022 "2,389.13" "15.82" "2,373.31" "0.11" +181 06/08/2022 "0.11" "0.00" "0.11" "0.00" +2022 Totals "11,945.76" "235.24" "11,710.52" -Grand Totals "430,043.40" "180,043.40" "250,000.00" +Grand Totals "430,043.51" "180,043.51" "250,000.00" -"Last interest amount decreased by 0.11 due to rounding." \ No newline at end of file diff --git a/test/fixtures/FEC_example_3_3_1.xml b/test/fixtures/FEC_example_3_3_1.xml index bcb6d73..e8827e9 100644 --- a/test/fixtures/FEC_example_3_3_1.xml +++ b/test/fixtures/FEC_example_3_3_1.xml @@ -1,521 +1,521 @@ <?xml version='1.0' encoding='windows-1252'?> <TValueAmortizationSchedule> - <Rounding>1100</Rounding> + <Rounding>0</Rounding> <Compounding>6</Compounding> <NominalAnnualRate>0.08</NominalAnnualRate> <APR>0.08</APR> - <FinanceCharge>1800434000</FinanceCharge> + <FinanceCharge>1800435100</FinanceCharge> <AmountFinanced>2500000000</AmountFinanced> - <TotalOfPayments>4300434000</TotalOfPayments> + <TotalOfPayments>4300435100</TotalOfPayments> <AmortizationLine> <AmortizationLineType>8</AmortizationLineType> <Date>05/08/2007</Date> <Loan1Amount>2500000000</Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount></Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>0</InterestAccrued> <InterestPaid>0</InterestPaid> <PrincipalPaid>0</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2500000000</PrincipalBalance> <TotalBalance>2500000000</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>06/08/2007</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16666700</InterestAccrued> <InterestPaid>16666700</InterestPaid> <PrincipalPaid>7224600</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2492775400</PrincipalBalance> <TotalBalance>2492775400</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>07/08/2007</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16618500</InterestAccrued> <InterestPaid>16618500</InterestPaid> <PrincipalPaid>7272800</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2485502600</PrincipalBalance> <TotalBalance>2485502600</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>08/08/2007</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16570000</InterestAccrued> <InterestPaid>16570000</InterestPaid> <PrincipalPaid>7321300</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2478181300</PrincipalBalance> <TotalBalance>2478181300</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>09/08/2007</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16521200</InterestAccrued> <InterestPaid>16521200</InterestPaid> <PrincipalPaid>7370100</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2470811200</PrincipalBalance> <TotalBalance>2470811200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>10/08/2007</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16472100</InterestAccrued> <InterestPaid>16472100</InterestPaid> <PrincipalPaid>7419200</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2463392000</PrincipalBalance> <TotalBalance>2463392000</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>11/08/2007</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16422600</InterestAccrued> <InterestPaid>16422600</InterestPaid> <PrincipalPaid>7468700</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2455923300</PrincipalBalance> <TotalBalance>2455923300</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>12/08/2007</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16372800</InterestAccrued> <InterestPaid>16372800</InterestPaid> <PrincipalPaid>7518500</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2448404800</PrincipalBalance> <TotalBalance>2448404800</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>51</AmortizationLineType> <Date>12/31/2007</Date> <Loan1Amount>2500000000</Loan1Amount> <Loan2Amount>0</Loan2Amount> <Loan3Amount>0</Loan3Amount> <Payment1Amount>167239100</Payment1Amount> <Payment2Amount>0</Payment2Amount> <Payment3Amount>0</Payment3Amount> <InterestAccrued>115643900</InterestAccrued> <InterestPaid>115643900</InterestPaid> <PrincipalPaid>51595200</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2448404800</PrincipalBalance> <TotalBalance>2448404800</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>01/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16322700</InterestAccrued> <InterestPaid>16322700</InterestPaid> <PrincipalPaid>7568600</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2440836200</PrincipalBalance> <TotalBalance>2440836200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>02/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16272200</InterestAccrued> <InterestPaid>16272200</InterestPaid> <PrincipalPaid>7619100</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2433217100</PrincipalBalance> <TotalBalance>2433217100</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>03/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16221400</InterestAccrued> <InterestPaid>16221400</InterestPaid> <PrincipalPaid>7669900</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2425547200</PrincipalBalance> <TotalBalance>2425547200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>04/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16170300</InterestAccrued> <InterestPaid>16170300</InterestPaid> <PrincipalPaid>7721000</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2417826200</PrincipalBalance> <TotalBalance>2417826200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>05/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16118800</InterestAccrued> <InterestPaid>16118800</InterestPaid> <PrincipalPaid>7772500</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2410053700</PrincipalBalance> <TotalBalance>2410053700</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>06/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16067000</InterestAccrued> <InterestPaid>16067000</InterestPaid> <PrincipalPaid>7824300</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2402229400</PrincipalBalance> <TotalBalance>2402229400</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>07/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>16014900</InterestAccrued> <InterestPaid>16014900</InterestPaid> <PrincipalPaid>7876400</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2394353000</PrincipalBalance> <TotalBalance>2394353000</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>08/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15962400</InterestAccrued> <InterestPaid>15962400</InterestPaid> <PrincipalPaid>7928900</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2386424100</PrincipalBalance> <TotalBalance>2386424100</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>09/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15909500</InterestAccrued> <InterestPaid>15909500</InterestPaid> <PrincipalPaid>7981800</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2378442300</PrincipalBalance> <TotalBalance>2378442300</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>10/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15856300</InterestAccrued> <InterestPaid>15856300</InterestPaid> <PrincipalPaid>8035000</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2370407300</PrincipalBalance> <TotalBalance>2370407300</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>11/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15802700</InterestAccrued> <InterestPaid>15802700</InterestPaid> <PrincipalPaid>8088600</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2362318700</PrincipalBalance> <TotalBalance>2362318700</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>12/08/2008</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15748800</InterestAccrued> <InterestPaid>15748800</InterestPaid> <PrincipalPaid>8142500</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2354176200</PrincipalBalance> <TotalBalance>2354176200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>51</AmortizationLineType> <Date>12/31/2008</Date> <Loan1Amount>0</Loan1Amount> <Loan2Amount>0</Loan2Amount> <Loan3Amount>0</Loan3Amount> <Payment1Amount>286695600</Payment1Amount> <Payment2Amount>0</Payment2Amount> <Payment3Amount>0</Payment3Amount> <InterestAccrued>192467000</InterestAccrued> <InterestPaid>192467000</InterestPaid> <PrincipalPaid>94228600</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2354176200</PrincipalBalance> <TotalBalance>2354176200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>01/08/2009</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15694500</InterestAccrued> <InterestPaid>15694500</InterestPaid> <PrincipalPaid>8196800</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2345979400</PrincipalBalance> <TotalBalance>2345979400</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>02/08/2009</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15639900</InterestAccrued> <InterestPaid>15639900</InterestPaid> <PrincipalPaid>8251400</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2337728000</PrincipalBalance> <TotalBalance>2337728000</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>03/08/2009</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15584900</InterestAccrued> <InterestPaid>15584900</InterestPaid> <PrincipalPaid>8306400</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2329421600</PrincipalBalance> <TotalBalance>2329421600</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>04/08/2009</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15529500</InterestAccrued> <InterestPaid>15529500</InterestPaid> <PrincipalPaid>8361800</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2321059800</PrincipalBalance> <TotalBalance>2321059800</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>05/08/2009</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15473700</InterestAccrued> <InterestPaid>15473700</InterestPaid> <PrincipalPaid>8417600</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2312642200</PrincipalBalance> <TotalBalance>2312642200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>06/08/2009</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>15417600</InterestAccrued> <InterestPaid>15417600</InterestPaid> <PrincipalPaid>8473700</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>2304168500</PrincipalBalance> <TotalBalance>2304168500</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>07/08/2009</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> @@ -3017,559 +3017,577 @@ <AmortizationLineType>9</AmortizationLineType> <Date>03/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>3923700</InterestAccrued> <InterestPaid>3923700</InterestPaid> <PrincipalPaid>19967600</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>568585900</PrincipalBalance> <TotalBalance>568585900</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>04/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>3790600</InterestAccrued> <InterestPaid>3790600</InterestPaid> <PrincipalPaid>20100700</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>548485200</PrincipalBalance> <TotalBalance>548485200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>05/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>3656600</InterestAccrued> <InterestPaid>3656600</InterestPaid> <PrincipalPaid>20234700</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>528250500</PrincipalBalance> <TotalBalance>528250500</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>06/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>3521700</InterestAccrued> <InterestPaid>3521700</InterestPaid> <PrincipalPaid>20369600</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>507880900</PrincipalBalance> <TotalBalance>507880900</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>07/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>3385900</InterestAccrued> <InterestPaid>3385900</InterestPaid> <PrincipalPaid>20505400</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>487375500</PrincipalBalance> <TotalBalance>487375500</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>08/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>3249200</InterestAccrued> <InterestPaid>3249200</InterestPaid> <PrincipalPaid>20642100</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>466733400</PrincipalBalance> <TotalBalance>466733400</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>09/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>3111600</InterestAccrued> <InterestPaid>3111600</InterestPaid> <PrincipalPaid>20779700</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>445953700</PrincipalBalance> <TotalBalance>445953700</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>10/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>2973000</InterestAccrued> <InterestPaid>2973000</InterestPaid> <PrincipalPaid>20918300</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>425035400</PrincipalBalance> <TotalBalance>425035400</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>11/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>2833600</InterestAccrued> <InterestPaid>2833600</InterestPaid> <PrincipalPaid>21057700</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>403977700</PrincipalBalance> <TotalBalance>403977700</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>12/08/2020</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>2693200</InterestAccrued> <InterestPaid>2693200</InterestPaid> <PrincipalPaid>21198100</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>382779600</PrincipalBalance> <TotalBalance>382779600</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>51</AmortizationLineType> <Date>12/31/2020</Date> <Loan1Amount>0</Loan1Amount> <Loan2Amount>0</Loan2Amount> <Loan3Amount>0</Loan3Amount> <Payment1Amount>286695600</Payment1Amount> <Payment2Amount>0</Payment2Amount> <Payment3Amount>0</Payment3Amount> <InterestAccrued>41382300</InterestAccrued> <InterestPaid>41382300</InterestPaid> <PrincipalPaid>245313300</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>382779600</PrincipalBalance> <TotalBalance>382779600</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>01/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>2551900</InterestAccrued> <InterestPaid>2551900</InterestPaid> <PrincipalPaid>21339400</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>361440200</PrincipalBalance> <TotalBalance>361440200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>02/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>2409600</InterestAccrued> <InterestPaid>2409600</InterestPaid> <PrincipalPaid>21481700</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>339958500</PrincipalBalance> <TotalBalance>339958500</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>03/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>2266400</InterestAccrued> <InterestPaid>2266400</InterestPaid> <PrincipalPaid>21624900</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>318333600</PrincipalBalance> <TotalBalance>318333600</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>04/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>2122200</InterestAccrued> <InterestPaid>2122200</InterestPaid> <PrincipalPaid>21769100</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>296564500</PrincipalBalance> <TotalBalance>296564500</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>05/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>1977100</InterestAccrued> <InterestPaid>1977100</InterestPaid> <PrincipalPaid>21914200</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>274650300</PrincipalBalance> <TotalBalance>274650300</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>06/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>1831000</InterestAccrued> <InterestPaid>1831000</InterestPaid> <PrincipalPaid>22060300</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>252590000</PrincipalBalance> <TotalBalance>252590000</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>07/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>1683900</InterestAccrued> <InterestPaid>1683900</InterestPaid> <PrincipalPaid>22207400</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>230382600</PrincipalBalance> <TotalBalance>230382600</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>08/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>1535900</InterestAccrued> <InterestPaid>1535900</InterestPaid> <PrincipalPaid>22355400</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>208027200</PrincipalBalance> <TotalBalance>208027200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>09/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>1386800</InterestAccrued> <InterestPaid>1386800</InterestPaid> <PrincipalPaid>22504500</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>185522700</PrincipalBalance> <TotalBalance>185522700</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>10/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>1236800</InterestAccrued> <InterestPaid>1236800</InterestPaid> <PrincipalPaid>22654500</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>162868200</PrincipalBalance> <TotalBalance>162868200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>11/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>1085800</InterestAccrued> <InterestPaid>1085800</InterestPaid> <PrincipalPaid>22805500</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>140062700</PrincipalBalance> <TotalBalance>140062700</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>12/08/2021</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>933800</InterestAccrued> <InterestPaid>933800</InterestPaid> <PrincipalPaid>22957500</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>117105200</PrincipalBalance> <TotalBalance>117105200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>51</AmortizationLineType> <Date>12/31/2021</Date> <Loan1Amount>0</Loan1Amount> <Loan2Amount>0</Loan2Amount> <Loan3Amount>0</Loan3Amount> <Payment1Amount>286695600</Payment1Amount> <Payment2Amount>0</Payment2Amount> <Payment3Amount>0</Payment3Amount> <InterestAccrued>21021200</InterestAccrued> <InterestPaid>21021200</InterestPaid> <PrincipalPaid>265674400</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>117105200</PrincipalBalance> <TotalBalance>117105200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>01/08/2022</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>780700</InterestAccrued> <InterestPaid>780700</InterestPaid> <PrincipalPaid>23110600</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>93994600</PrincipalBalance> <TotalBalance>93994600</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>02/08/2022</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>626600</InterestAccrued> <InterestPaid>626600</InterestPaid> <PrincipalPaid>23264700</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>70729900</PrincipalBalance> <TotalBalance>70729900</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>03/08/2022</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>471500</InterestAccrued> <InterestPaid>471500</InterestPaid> <PrincipalPaid>23419800</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>47310100</PrincipalBalance> <TotalBalance>47310100</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>04/08/2022</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> <InterestAccrued>315400</InterestAccrued> <InterestPaid>315400</InterestPaid> <PrincipalPaid>23575900</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>23734200</PrincipalBalance> <TotalBalance>23734200</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>9</AmortizationLineType> <Date>05/08/2022</Date> <Loan1Amount></Loan1Amount> <Loan2Amount></Loan2Amount> <Loan3Amount></Loan3Amount> <Payment1Amount>23891300</Payment1Amount> <Payment2Amount></Payment2Amount> <Payment3Amount></Payment3Amount> - <InterestAccrued>157100</InterestAccrued> - <InterestPaid>157100</InterestPaid> - <PrincipalPaid>23734200</PrincipalPaid> + <InterestAccrued>158200</InterestAccrued> + <InterestPaid>158200</InterestPaid> + <PrincipalPaid>23733100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1100</PrincipalBalance> + <TotalBalance>1100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2022</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>1100</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>0</InterestAccrued> + <InterestPaid>0</InterestPaid> + <PrincipalPaid>1100</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>0</PrincipalBalance> <TotalBalance>0</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>51</AmortizationLineType> <Date>12/31/2022</Date> <Loan1Amount>0</Loan1Amount> <Loan2Amount>0</Loan2Amount> <Loan3Amount>0</Loan3Amount> - <Payment1Amount>119456500</Payment1Amount> + <Payment1Amount>119457600</Payment1Amount> <Payment2Amount>0</Payment2Amount> <Payment3Amount>0</Payment3Amount> - <InterestAccrued>2351300</InterestAccrued> - <InterestPaid>2351300</InterestPaid> + <InterestAccrued>2352400</InterestAccrued> + <InterestPaid>2352400</InterestPaid> <PrincipalPaid>117105200</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>0</PrincipalBalance> <TotalBalance>0</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> <AmortizationLine> <AmortizationLineType>52</AmortizationLineType> - <Date>05/31/2022</Date> + <Date>06/30/2022</Date> <Loan1Amount>2500000000</Loan1Amount> <Loan2Amount>0</Loan2Amount> <Loan3Amount>0</Loan3Amount> - <Payment1Amount>4300434000</Payment1Amount> + <Payment1Amount>4300435100</Payment1Amount> <Payment2Amount>0</Payment2Amount> <Payment3Amount>0</Payment3Amount> - <InterestAccrued>1800434000</InterestAccrued> - <InterestPaid>1800434000</InterestPaid> + <InterestAccrued>1800435100</InterestAccrued> + <InterestPaid>1800435100</InterestPaid> <PrincipalPaid>2500000000</PrincipalPaid> <UnpaidInterestBalance>0</UnpaidInterestBalance> <PrincipalBalance>0</PrincipalBalance> <TotalBalance>0</TotalBalance> <RateChangeRate></RateChangeRate> <RateChangeCompounding>13</RateChangeCompounding> </AmortizationLine> </TValueAmortizationSchedule> \ No newline at end of file diff --git a/test/test_helper.rb b/test/test_helper.rb index f92e404..c72076a 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,3 +1,37 @@ $:.unshift(File.dirname(__FILE__) + "/../lib/") require 'test/unit' require 'stater' + +require 'rubygems' +require 'hpricot' + +class Test::Unit::TestCase + def assert_schedule(xml_file, schedule) + control_schedule = [] + doc = Hpricot(open(xml_file)) + + lines = (doc/:tvalueamortizationschedule/:amortizationline) + lines.each do |line| + if line.search(:amortizationlinetype).innerHTML == '9' + payment = line.search(:payment1amount).innerHTML.gsub(/(\d{2})\d{2}$/, '.\1') + interest_paid = line.search(:interestpaid).innerHTML.gsub(/(\d{2})\d{2}$/, '.\1') + principal_paid = line.search(:principalpaid).innerHTML.gsub(/(\d{2})\d{2}$/, '.\1') + principal_balance = line.search(:principalbalance).innerHTML.gsub(/(\d{2})\d{2}$/, '.\1') + control_schedule << Struct::Payment.new(nil, payment, principal_paid, interest_paid, principal_balance) + end + end + + # assert_equal control_schedule.size, schedule.size, "The number of amortization lines is not the same." + + schedule.each_with_index do |line, index| + assert_equal control_schedule[index].payment, line.payment.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), + "payment at amortization line: #{index}" + assert_equal control_schedule[index].interest, line.interest.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), + "interest at amortization line #{index}" + assert_equal control_schedule[index].principal, line.principal.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), + "principal at amortization line #{index}" + assert_equal control_schedule[index].principal_balance, line.principal_balance.to_s('F').gsub(/\.(\d{1})$/, '.\10').gsub(/^0/, ''), + "principal_balance at amortization line #{index}" + end + end +end diff --git a/test/unit/amortization_test.rb b/test/unit/amortization_test.rb index 7d57927..6bf038f 100644 --- a/test/unit/amortization_test.rb +++ b/test/unit/amortization_test.rb @@ -1,48 +1,44 @@ require File.dirname(__FILE__) + '/../test_helper' class Stater::AmortizationTest < Test::Unit::TestCase def test_new_amortization amortization = Stater::Amortization.new - # assert_equal [], amortization.schedule + assert_equal [], amortization.schedule assert_nil amortization.principal assert_nil amortization.periodic_rate assert_nil amortization.periods end def test_payment principal = 250000.00 periodic_rate = 0.08 / 12 periods = 15 * 12 amortization = Stater::Amortization.new(250000.00, periodic_rate, periods) - assert_kind_of BigDecimal, amortization.payment - assert_equal BigDecimal('2389.13'), amortization.payment + assert_kind_of BigDecimal, amortization.calculate_payment + assert_equal BigDecimal('2389.13'), amortization.calculate_payment end def test_schedule principal = 250000.00 periodic_rate = 0.08 / 12 periods = 15 * 12 amortization = Stater::Amortization.new(principal, periodic_rate, periods) assert_kind_of BigDecimal, amortization.principal assert_equal BigDecimal(principal.to_s), amortization.principal assert_kind_of BigDecimal, amortization.periodic_rate assert_equal BigDecimal(periodic_rate.to_s), amortization.periodic_rate assert_kind_of Fixnum, amortization.periods assert_equal periods, amortization.periods - payment = amortization.schedule.first - assert_kind_of Fixnum, payment.payment_number - assert_kind_of BigDecimal, payment.payment - assert_kind_of BigDecimal, payment.principal - assert_kind_of BigDecimal, payment.interest - assert_kind_of BigDecimal, payment.remaining_principal + # Compare to TValue schedules - they should match exactly + assert_schedule('./../fixtures/FEC_example_3_3_1.xml', amortization.schedule) end end \ No newline at end of file
infused/stater
a5870497f283f8c969b2d1d46456573148f5e9f1
BigDecimal conversion
diff --git a/lib/stater/amortization.rb b/lib/stater/amortization.rb index 0a4517b..f0a19e6 100644 --- a/lib/stater/amortization.rb +++ b/lib/stater/amortization.rb @@ -1,46 +1,50 @@ Struct.new('Payment', :payment_number, :payment, :principal, :interest, :remaining_principal) +class NilClass + def to_d + nil + end +end module Stater class Amortization attr_accessor :principal attr_accessor :periodic_rate attr_accessor :periods def initialize(principal = nil, periodic_rate = nil, periods = nil) @schedule = [] - @principal, @periodic_rate, @periods = principal, periodic_rate, periods - + @principal, @periodic_rate, @periods = principal.to_d, periodic_rate.to_d, periods end # Calculates the payment when given the principal amount and interest rate def payment x = @periodic_rate * @principal * ((1 + @periodic_rate)**@periods) y = ((1 + @periodic_rate)**@periods) - 1 result = x / y - BigDecimal(result.to_s).round(2).to_f + BigDecimal(result.to_s).round(2) #.to_f end def schedule # return [] if @principal.nil? or @period_rate.nil? or @periods.nil? payments = [] pmt = payment - remaining_principal = @principal.to_d + remaining_principal = @principal payment_number = 0 while remaining_principal > 0 do payment_number += 1 interest = remaining_principal * @periodic_rate principal = pmt - interest remaining_principal = remaining_principal - principal payments << Struct::Payment.new(payment_number, pmt, principal, interest, remaining_principal) end payments end end end \ No newline at end of file diff --git a/test/unit/amortization_test.rb b/test/unit/amortization_test.rb index 72cfd85..7d57927 100644 --- a/test/unit/amortization_test.rb +++ b/test/unit/amortization_test.rb @@ -1,31 +1,48 @@ require File.dirname(__FILE__) + '/../test_helper' class Stater::AmortizationTest < Test::Unit::TestCase def test_new_amortization amortization = Stater::Amortization.new # assert_equal [], amortization.schedule assert_nil amortization.principal assert_nil amortization.periodic_rate assert_nil amortization.periods end def test_payment principal = 250000.00 periodic_rate = 0.08 / 12 periods = 15 * 12 amortization = Stater::Amortization.new(250000.00, periodic_rate, periods) - assert_equal '2389.13', amortization.payment.to_s + + assert_kind_of BigDecimal, amortization.payment + assert_equal BigDecimal('2389.13'), amortization.payment end def test_schedule principal = 250000.00 periodic_rate = 0.08 / 12 periods = 15 * 12 - amortization = Stater::Amortization.new(250000.00, periodic_rate, periods) - # assert_equal '', amortization.schedule + amortization = Stater::Amortization.new(principal, periodic_rate, periods) + + assert_kind_of BigDecimal, amortization.principal + assert_equal BigDecimal(principal.to_s), amortization.principal + + assert_kind_of BigDecimal, amortization.periodic_rate + assert_equal BigDecimal(periodic_rate.to_s), amortization.periodic_rate + + assert_kind_of Fixnum, amortization.periods + assert_equal periods, amortization.periods + + payment = amortization.schedule.first + assert_kind_of Fixnum, payment.payment_number + assert_kind_of BigDecimal, payment.payment + assert_kind_of BigDecimal, payment.principal + assert_kind_of BigDecimal, payment.interest + assert_kind_of BigDecimal, payment.remaining_principal end end \ No newline at end of file
infused/stater
0f8cbf1d9b3e0aedcc11e64e57dcd2448ef3bf6d
Unrounded amort schedule
diff --git a/lib/stater.rb b/lib/stater.rb index 88e3598..75533e5 100644 --- a/lib/stater.rb +++ b/lib/stater.rb @@ -1,5 +1,6 @@ require 'bigdecimal' +require 'bigdecimal/util' require 'stater/tvm' require 'stater/base' require 'stater/amortization' diff --git a/lib/stater/amortization.rb b/lib/stater/amortization.rb index 047c74e..0a4517b 100644 --- a/lib/stater/amortization.rb +++ b/lib/stater/amortization.rb @@ -1,24 +1,46 @@ +Struct.new('Payment', :payment_number, :payment, :principal, :interest, :remaining_principal) + module Stater class Amortization - class << self - # Calculates the payment when given the principal amount and interest rate - def payment_amount(principal_amount, interest_rate, number_of_payments) - x = interest_rate * principal_amount * ((1 + interest_rate) ** number_of_payments) - y = ((1 + interest_rate) ** number_of_payments) - 1 - return BigDecimal((x / y).to_s).round(2).to_f - end + attr_accessor :principal + attr_accessor :periodic_rate + attr_accessor :periods - # Calculates the principal when given the periodic payment and interest rate - def principal(payment_amount, interest_rate, number_of_payments) + def initialize(principal = nil, periodic_rate = nil, periods = nil) + @schedule = [] + @principal, @periodic_rate, @periods = principal, periodic_rate, periods - end + end - # Calculates the annual interest rate when given the principal amount and periodic payment - def interest(principal_amount, payment_amount, number_of_payments) + # Calculates the payment when given the principal amount and interest rate + def payment + x = @periodic_rate * @principal * ((1 + @periodic_rate)**@periods) + y = ((1 + @periodic_rate)**@periods) - 1 + result = x / y + BigDecimal(result.to_s).round(2).to_f + end + + def schedule + # return [] if @principal.nil? or @period_rate.nil? or @periods.nil? + + payments = [] + pmt = payment + remaining_principal = @principal.to_d + payment_number = 0 + while remaining_principal > 0 do + payment_number += 1 + + interest = remaining_principal * @periodic_rate + principal = pmt - interest + remaining_principal = remaining_principal - principal + + payments << Struct::Payment.new(payment_number, pmt, principal, interest, remaining_principal) end + payments end + end end \ No newline at end of file diff --git a/lib/stater/tvm.rb b/lib/stater/tvm.rb index f503856..a9c1f5d 100644 --- a/lib/stater/tvm.rb +++ b/lib/stater/tvm.rb @@ -1,78 +1,76 @@ module Stater class TVM include Math class << self # Calculates the future value # pv = present value - # r = nominal interest rate - # y = years - # n = periods per year - def fv(pv, r, y, n) - pv * ((1 + (r / n))**(y * n)) + # r = periodic interest rate + # n = number of compounding periods + def fv(pv, r, n) + pv * ((1 + r)**n) end # Calulates the present value # fv = future value - # r = nominal interest rate - # y = years - # n = periods per year - def pv(fv, r, y, n) - fv / ((1 + (r / n))**(y * n)) + # r = periodic interest rate + # n = number of compounding periods + def pv(fv, r, n) + fv / ((1 + r)**n) end # Calculates the nomical interest rate # pv = present value # fv = future value # y = years # n = compounding periods per year def i(pv, fv, y, n) n * ((fv / pv) ** (1 / (y.to_f * n)) - 1) end # Calculates the number of years # pv = present value # fv = future value # r = nominal interest rate # n = compounding periods per year def y(pv, fv, r, n) Math.log(fv / pv) / (n * Math.log(1 + (r / n))) end # Converts the nomical interest rate to APR (annual percentage rate) # r = nominal interest rate # n = compounding periods per year def i_to_apr(r, n) ((1 + (r / n)) ** n) - 1 end # Converts APR (annual percentage rate) to the nomical interest rate # apr = annual percentage rate # n = compounding periods per year def apr_to_i(apr, n) n * ((1 + apr) ** (1/n.to_f) - 1) end # Converts EAR (effective annual rate) to APR (annual percentage rate) # apr = annual percentage rate # n = compounding periods per year def apr_to_ear(apr, n) ((1 + apr / n)**n) - 1 end # Converts APR (annual percentage rate) to EAR (effective annual rate) # ear = effective annual rate # n = compounding periods per year def ear_to_apr(ear, n) n * ((1 + ear)**(1 / n.to_f) - 1) end alias_method :present_value, :pv alias_method :future_value, :fv alias_method :interest, :i alias_method :years, :y alias_method :annual_interest_to_apr, :i_to_apr alias_method :apr_to_annual_interest, :apr_to_i end end end \ No newline at end of file diff --git a/test/fixtures/FEC_example_3_3_1.csv b/test/fixtures/FEC_example_3_3_1.csv new file mode 100644 index 0000000..ab18642 --- /dev/null +++ b/test/fixtures/FEC_example_3_3_1.csv @@ -0,0 +1,234 @@ +"Test1" + +Compound Period: Monthly + +Nominal Annual Rate: 8.000 % + +CASH FLOW DATA + + Event Date Amount Number Period End Date +1 Loan 05/08/2007 "250,000.00" 1 +2 Payment 06/08/2007 "2,389.13" 180 Monthly 05/08/2022 + +AMORTIZATION SCHEDULE - Normal Amortization + +# Date Payment Interest Principal Balance +Loan 05/08/2007 "250,000.00" +1 06/08/2007 "2,389.13" "1,666.67" "722.46" "249,277.54" +2 07/08/2007 "2,389.13" "1,661.85" "727.28" "248,550.26" +3 08/08/2007 "2,389.13" "1,657.00" "732.13" "247,818.13" +4 09/08/2007 "2,389.13" "1,652.12" "737.01" "247,081.12" +5 10/08/2007 "2,389.13" "1,647.21" "741.92" "246,339.20" +6 11/08/2007 "2,389.13" "1,642.26" "746.87" "245,592.33" +7 12/08/2007 "2,389.13" "1,637.28" "751.85" "244,840.48" +2007 Totals "16,723.91" "11,564.39" "5,159.52" + +8 01/08/2008 "2,389.13" "1,632.27" "756.86" "244,083.62" +9 02/08/2008 "2,389.13" "1,627.22" "761.91" "243,321.71" +10 03/08/2008 "2,389.13" "1,622.14" "766.99" "242,554.72" +11 04/08/2008 "2,389.13" "1,617.03" "772.10" "241,782.62" +12 05/08/2008 "2,389.13" "1,611.88" "777.25" "241,005.37" +13 06/08/2008 "2,389.13" "1,606.70" "782.43" "240,222.94" +14 07/08/2008 "2,389.13" "1,601.49" "787.64" "239,435.30" +15 08/08/2008 "2,389.13" "1,596.24" "792.89" "238,642.41" +16 09/08/2008 "2,389.13" "1,590.95" "798.18" "237,844.23" +17 10/08/2008 "2,389.13" "1,585.63" "803.50" "237,040.73" +18 11/08/2008 "2,389.13" "1,580.27" "808.86" "236,231.87" +19 12/08/2008 "2,389.13" "1,574.88" "814.25" "235,417.62" +2008 Totals "28,669.56" "19,246.70" "9,422.86" + +20 01/08/2009 "2,389.13" "1,569.45" "819.68" "234,597.94" +21 02/08/2009 "2,389.13" "1,563.99" "825.14" "233,772.80" +22 03/08/2009 "2,389.13" "1,558.49" "830.64" "232,942.16" +23 04/08/2009 "2,389.13" "1,552.95" "836.18" "232,105.98" +24 05/08/2009 "2,389.13" "1,547.37" "841.76" "231,264.22" +25 06/08/2009 "2,389.13" "1,541.76" "847.37" "230,416.85" +26 07/08/2009 "2,389.13" "1,536.11" "853.02" "229,563.83" +27 08/08/2009 "2,389.13" "1,530.43" "858.70" "228,705.13" +28 09/08/2009 "2,389.13" "1,524.70" "864.43" "227,840.70" +29 10/08/2009 "2,389.13" "1,518.94" "870.19" "226,970.51" +30 11/08/2009 "2,389.13" "1,513.14" "875.99" "226,094.52" +31 12/08/2009 "2,389.13" "1,507.30" "881.83" "225,212.69" +2009 Totals "28,669.56" "18,464.63" "10,204.93" + +32 01/08/2010 "2,389.13" "1,501.42" "887.71" "224,324.98" +33 02/08/2010 "2,389.13" "1,495.50" "893.63" "223,431.35" +34 03/08/2010 "2,389.13" "1,489.54" "899.59" "222,531.76" +35 04/08/2010 "2,389.13" "1,483.55" "905.58" "221,626.18" +36 05/08/2010 "2,389.13" "1,477.51" "911.62" "220,714.56" +37 06/08/2010 "2,389.13" "1,471.43" "917.70" "219,796.86" +38 07/08/2010 "2,389.13" "1,465.31" "923.82" "218,873.04" +39 08/08/2010 "2,389.13" "1,459.15" "929.98" "217,943.06" +40 09/08/2010 "2,389.13" "1,452.95" "936.18" "217,006.88" +41 10/08/2010 "2,389.13" "1,446.71" "942.42" "216,064.46" +42 11/08/2010 "2,389.13" "1,440.43" "948.70" "215,115.76" +43 12/08/2010 "2,389.13" "1,434.11" "955.02" "214,160.74" +2010 Totals "28,669.56" "17,617.61" "11,051.95" + +44 01/08/2011 "2,389.13" "1,427.74" "961.39" "213,199.35" +45 02/08/2011 "2,389.13" "1,421.33" "967.80" "212,231.55" +46 03/08/2011 "2,389.13" "1,414.88" "974.25" "211,257.30" +47 04/08/2011 "2,389.13" "1,408.38" "980.75" "210,276.55" +48 05/08/2011 "2,389.13" "1,401.84" "987.29" "209,289.26" +49 06/08/2011 "2,389.13" "1,395.26" "993.87" "208,295.39" +50 07/08/2011 "2,389.13" "1,388.64" "1,000.49" "207,294.90" +51 08/08/2011 "2,389.13" "1,381.97" "1,007.16" "206,287.74" +52 09/08/2011 "2,389.13" "1,375.25" "1,013.88" "205,273.86" +53 10/08/2011 "2,389.13" "1,368.49" "1,020.64" "204,253.22" +54 11/08/2011 "2,389.13" "1,361.69" "1,027.44" "203,225.78" +55 12/08/2011 "2,389.13" "1,354.84" "1,034.29" "202,191.49" +2011 Totals "28,669.56" "16,700.31" "11,969.25" + +56 01/08/2012 "2,389.13" "1,347.94" "1,041.19" "201,150.30" +57 02/08/2012 "2,389.13" "1,341.00" "1,048.13" "200,102.17" +58 03/08/2012 "2,389.13" "1,334.01" "1,055.12" "199,047.05" +59 04/08/2012 "2,389.13" "1,326.98" "1,062.15" "197,984.90" +60 05/08/2012 "2,389.13" "1,319.90" "1,069.23" "196,915.67" +61 06/08/2012 "2,389.13" "1,312.77" "1,076.36" "195,839.31" +62 07/08/2012 "2,389.13" "1,305.60" "1,083.53" "194,755.78" +63 08/08/2012 "2,389.13" "1,298.37" "1,090.76" "193,665.02" +64 09/08/2012 "2,389.13" "1,291.10" "1,098.03" "192,566.99" +65 10/08/2012 "2,389.13" "1,283.78" "1,105.35" "191,461.64" +66 11/08/2012 "2,389.13" "1,276.41" "1,112.72" "190,348.92" +67 12/08/2012 "2,389.13" "1,268.99" "1,120.14" "189,228.78" +2012 Totals "28,669.56" "15,706.85" "12,962.71" + +68 01/08/2013 "2,389.13" "1,261.53" "1,127.60" "188,101.18" +69 02/08/2013 "2,389.13" "1,254.01" "1,135.12" "186,966.06" +70 03/08/2013 "2,389.13" "1,246.44" "1,142.69" "185,823.37" +71 04/08/2013 "2,389.13" "1,238.82" "1,150.31" "184,673.06" +72 05/08/2013 "2,389.13" "1,231.15" "1,157.98" "183,515.08" +73 06/08/2013 "2,389.13" "1,223.43" "1,165.70" "182,349.38" +74 07/08/2013 "2,389.13" "1,215.66" "1,173.47" "181,175.91" +75 08/08/2013 "2,389.13" "1,207.84" "1,181.29" "179,994.62" +76 09/08/2013 "2,389.13" "1,199.96" "1,189.17" "178,805.45" +77 10/08/2013 "2,389.13" "1,192.04" "1,197.09" "177,608.36" +78 11/08/2013 "2,389.13" "1,184.06" "1,205.07" "176,403.29" +79 12/08/2013 "2,389.13" "1,176.02" "1,213.11" "175,190.18" +2013 Totals "28,669.56" "14,630.96" "14,038.60" + +80 01/08/2014 "2,389.13" "1,167.93" "1,221.20" "173,968.98" +81 02/08/2014 "2,389.13" "1,159.79" "1,229.34" "172,739.64" +82 03/08/2014 "2,389.13" "1,151.60" "1,237.53" "171,502.11" +83 04/08/2014 "2,389.13" "1,143.35" "1,245.78" "170,256.33" +84 05/08/2014 "2,389.13" "1,135.04" "1,254.09" "169,002.24" +85 06/08/2014 "2,389.13" "1,126.68" "1,262.45" "167,739.79" +86 07/08/2014 "2,389.13" "1,118.27" "1,270.86" "166,468.93" +87 08/08/2014 "2,389.13" "1,109.79" "1,279.34" "165,189.59" +88 09/08/2014 "2,389.13" "1,101.26" "1,287.87" "163,901.72" +89 10/08/2014 "2,389.13" "1,092.68" "1,296.45" "162,605.27" +90 11/08/2014 "2,389.13" "1,084.04" "1,305.09" "161,300.18" +91 12/08/2014 "2,389.13" "1,075.33" "1,313.80" "159,986.38" +2014 Totals "28,669.56" "13,465.76" "15,203.80" + +92 01/08/2015 "2,389.13" "1,066.58" "1,322.55" "158,663.83" +93 02/08/2015 "2,389.13" "1,057.76" "1,331.37" "157,332.46" +94 03/08/2015 "2,389.13" "1,048.88" "1,340.25" "155,992.21" +95 04/08/2015 "2,389.13" "1,039.95" "1,349.18" "154,643.03" +96 05/08/2015 "2,389.13" "1,030.95" "1,358.18" "153,284.85" +97 06/08/2015 "2,389.13" "1,021.90" "1,367.23" "151,917.62" +98 07/08/2015 "2,389.13" "1,012.78" "1,376.35" "150,541.27" +99 08/08/2015 "2,389.13" "1,003.61" "1,385.52" "149,155.75" +100 09/08/2015 "2,389.13" "994.37" "1,394.76" "147,760.99" +101 10/08/2015 "2,389.13" "985.07" "1,404.06" "146,356.93" +102 11/08/2015 "2,389.13" "975.71" "1,413.42" "144,943.51" +103 12/08/2015 "2,389.13" "966.29" "1,422.84" "143,520.67" +2015 Totals "28,669.56" "12,203.85" "16,465.71" + +104 01/08/2016 "2,389.13" "956.80" "1,432.33" "142,088.34" +105 02/08/2016 "2,389.13" "947.26" "1,441.87" "140,646.47" +106 03/08/2016 "2,389.13" "937.64" "1,451.49" "139,194.98" +107 04/08/2016 "2,389.13" "927.97" "1,461.16" "137,733.82" +108 05/08/2016 "2,389.13" "918.23" "1,470.90" "136,262.92" +109 06/08/2016 "2,389.13" "908.42" "1,480.71" "134,782.21" +110 07/08/2016 "2,389.13" "898.55" "1,490.58" "133,291.63" +111 08/08/2016 "2,389.13" "888.61" "1,500.52" "131,791.11" +112 09/08/2016 "2,389.13" "878.61" "1,510.52" "130,280.59" +113 10/08/2016 "2,389.13" "868.54" "1,520.59" "128,760.00" +114 11/08/2016 "2,389.13" "858.40" "1,530.73" "127,229.27" +115 12/08/2016 "2,389.13" "848.20" "1,540.93" "125,688.34" +2016 Totals "28,669.56" "10,837.23" "17,832.33" + +116 01/08/2017 "2,389.13" "837.92" "1,551.21" "124,137.13" +117 02/08/2017 "2,389.13" "827.58" "1,561.55" "122,575.58" +118 03/08/2017 "2,389.13" "817.17" "1,571.96" "121,003.62" +119 04/08/2017 "2,389.13" "806.69" "1,582.44" "119,421.18" +120 05/08/2017 "2,389.13" "796.14" "1,592.99" "117,828.19" +121 06/08/2017 "2,389.13" "785.52" "1,603.61" "116,224.58" +122 07/08/2017 "2,389.13" "774.83" "1,614.30" "114,610.28" +123 08/08/2017 "2,389.13" "764.07" "1,625.06" "112,985.22" +124 09/08/2017 "2,389.13" "753.23" "1,635.90" "111,349.32" +125 10/08/2017 "2,389.13" "742.33" "1,646.80" "109,702.52" +126 11/08/2017 "2,389.13" "731.35" "1,657.78" "108,044.74" +127 12/08/2017 "2,389.13" "720.30" "1,668.83" "106,375.91" +2017 Totals "28,669.56" "9,357.13" "19,312.43" + +128 01/08/2018 "2,389.13" "709.17" "1,679.96" "104,695.95" +129 02/08/2018 "2,389.13" "697.97" "1,691.16" "103,004.79" +130 03/08/2018 "2,389.13" "686.70" "1,702.43" "101,302.36" +131 04/08/2018 "2,389.13" "675.35" "1,713.78" "99,588.58" +132 05/08/2018 "2,389.13" "663.92" "1,725.21" "97,863.37" +133 06/08/2018 "2,389.13" "652.42" "1,736.71" "96,126.66" +134 07/08/2018 "2,389.13" "640.84" "1,748.29" "94,378.37" +135 08/08/2018 "2,389.13" "629.19" "1,759.94" "92,618.43" +136 09/08/2018 "2,389.13" "617.46" "1,771.67" "90,846.76" +137 10/08/2018 "2,389.13" "605.65" "1,783.48" "89,063.28" +138 11/08/2018 "2,389.13" "593.76" "1,795.37" "87,267.91" +139 12/08/2018 "2,389.13" "581.79" "1,807.34" "85,460.57" +2018 Totals "28,669.56" "7,754.22" "20,915.34" + +140 01/08/2019 "2,389.13" "569.74" "1,819.39" "83,641.18" +141 02/08/2019 "2,389.13" "557.61" "1,831.52" "81,809.66" +142 03/08/2019 "2,389.13" "545.40" "1,843.73" "79,965.93" +143 04/08/2019 "2,389.13" "533.11" "1,856.02" "78,109.91" +144 05/08/2019 "2,389.13" "520.73" "1,868.40" "76,241.51" +145 06/08/2019 "2,389.13" "508.28" "1,880.85" "74,360.66" +146 07/08/2019 "2,389.13" "495.74" "1,893.39" "72,467.27" +147 08/08/2019 "2,389.13" "483.12" "1,906.01" "70,561.26" +148 09/08/2019 "2,389.13" "470.41" "1,918.72" "68,642.54" +149 10/08/2019 "2,389.13" "457.62" "1,931.51" "66,711.03" +150 11/08/2019 "2,389.13" "444.74" "1,944.39" "64,766.64" +151 12/08/2019 "2,389.13" "431.78" "1,957.35" "62,809.29" +2019 Totals "28,669.56" "6,018.28" "22,651.28" + +152 01/08/2020 "2,389.13" "418.73" "1,970.40" "60,838.89" +153 02/08/2020 "2,389.13" "405.59" "1,983.54" "58,855.35" +154 03/08/2020 "2,389.13" "392.37" "1,996.76" "56,858.59" +155 04/08/2020 "2,389.13" "379.06" "2,010.07" "54,848.52" +156 05/08/2020 "2,389.13" "365.66" "2,023.47" "52,825.05" +157 06/08/2020 "2,389.13" "352.17" "2,036.96" "50,788.09" +158 07/08/2020 "2,389.13" "338.59" "2,050.54" "48,737.55" +159 08/08/2020 "2,389.13" "324.92" "2,064.21" "46,673.34" +160 09/08/2020 "2,389.13" "311.16" "2,077.97" "44,595.37" +161 10/08/2020 "2,389.13" "297.30" "2,091.83" "42,503.54" +162 11/08/2020 "2,389.13" "283.36" "2,105.77" "40,397.77" +163 12/08/2020 "2,389.13" "269.32" "2,119.81" "38,277.96" +2020 Totals "28,669.56" "4,138.23" "24,531.33" + +164 01/08/2021 "2,389.13" "255.19" "2,133.94" "36,144.02" +165 02/08/2021 "2,389.13" "240.96" "2,148.17" "33,995.85" +166 03/08/2021 "2,389.13" "226.64" "2,162.49" "31,833.36" +167 04/08/2021 "2,389.13" "212.22" "2,176.91" "29,656.45" +168 05/08/2021 "2,389.13" "197.71" "2,191.42" "27,465.03" +169 06/08/2021 "2,389.13" "183.10" "2,206.03" "25,259.00" +170 07/08/2021 "2,389.13" "168.39" "2,220.74" "23,038.26" +171 08/08/2021 "2,389.13" "153.59" "2,235.54" "20,802.72" +172 09/08/2021 "2,389.13" "138.68" "2,250.45" "18,552.27" +173 10/08/2021 "2,389.13" "123.68" "2,265.45" "16,286.82" +174 11/08/2021 "2,389.13" "108.58" "2,280.55" "14,006.27" +175 12/08/2021 "2,389.13" "93.38" "2,295.75" "11,710.52" +2021 Totals "28,669.56" "2,102.12" "26,567.44" + +176 01/08/2022 "2,389.13" "78.07" "2,311.06" "9,399.46" +177 02/08/2022 "2,389.13" "62.66" "2,326.47" "7,072.99" +178 03/08/2022 "2,389.13" "47.15" "2,341.98" "4,731.01" +179 04/08/2022 "2,389.13" "31.54" "2,357.59" "2,373.42" +180 05/08/2022 "2,389.13" "15.71" "2,373.42" "0.00" +2022 Totals "11,945.65" "235.13" "11,710.52" + + +Grand Totals "430,043.40" "180,043.40" "250,000.00" + + +"Last interest amount decreased by 0.11 due to rounding." + \ No newline at end of file diff --git a/test/fixtures/FEC_example_3_3_1.tv5 b/test/fixtures/FEC_example_3_3_1.tv5 new file mode 100644 index 0000000..99d11ea --- /dev/null +++ b/test/fixtures/FEC_example_3_3_1.tv5 @@ -0,0 +1,291 @@ +<?xml version='1.0' encoding='windows-1252'?> +<TValueCfm> + <TValueVersion>5.05.1</TValueVersion> + <LocaleID>1024</LocaleID> + <DateFormat>0</DateFormat> + <DateSeparator>/</DateSeparator> + <DecimalPlaces>2</DecimalPlaces> + <CFMLabel>Test1</CFMLabel> + <ComputeMethod>0</ComputeMethod> + <CanadianBasis>0</CanadianBasis> + <CanadianOddDays>0</CanadianOddDays> + <Compounding>6</Compounding> + <OpenBalance>0</OpenBalance> + <NominalAnnualRate>0.080000000000000</NominalAnnualRate> + <YearLength>365</YearLength> + <DefaultCompoundPeriod>6</DefaultCompoundPeriod> + <DefaultEventType>8</DefaultEventType> + <WholeDollarOnly>0</WholeDollarOnly> + <DefaultSecondEventDateSameAsFirst>0</DefaultSecondEventDateSameAsFirst> + <EventNames> + <IncludeStandardTValueEvent>1</IncludeStandardTValueEvent> + <IncludeUserLoanAndPaymentEvents>1</IncludeUserLoanAndPaymentEvents> + <IncludeUserDepositAndWithdrawalEvents>1</IncludeUserDepositAndWithdrawalEvents> + <MaxEventNameLength>15</MaxEventNameLength> + <UserLoanName1>Lease</UserLoanName1> + <UserLoanName2>Commission</UserLoanName2> + <UserLoanName3></UserLoanName3> + <UserPaymentName1>Lease Payment</UserPaymentName1> + <UserPaymentName2>Residual</UserPaymentName2> + <UserPaymentName3></UserPaymentName3> + <UserDepositName1>Invest</UserDepositName1> + <UserDepositName2></UserDepositName2> + <UserDepositName3></UserDepositName3> + <UserWithdrawalName1>Return</UserWithdrawalName1> + <UserWithdrawalName2></UserWithdrawalName2> + <UserWithdrawalName3></UserWithdrawalName3> + </EventNames> + <ReportOptions> + <CombineUserColumns>0</CombineUserColumns> + <TotalsOnly>0</TotalsOnly> + <IncludeCompoundPeriod>1</IncludeCompoundPeriod> + <IncludePageBreakBeforeAmortization>0</IncludePageBreakBeforeAmortization> + <IncludeLabel>1</IncludeLabel> + <IncludeDate>1</IncludeDate> + <IncludeTime>1</IncludeTime> + <IncludeQuarterlyTotals>0</IncludeQuarterlyTotals> + <IncludeAnnualTotals>1</IncludeAnnualTotals> + <IncludeGrandTotals>1</IncludeGrandTotals> + <IncludeAPRInformation>0</IncludeAPRInformation> + <IncludeNotes>1</IncludeNotes> + <IncludeNominalRate>1</IncludeNominalRate> + <IncludeEffectiveRate>0</IncludeEffectiveRate> + <IncludePeriodicRate>0</IncludePeriodicRate> + <IncludeDailyRate>0</IncludeDailyRate> + <IncludeRateChanges>1</IncludeRateChanges> + <PrintToFit>1</PrintToFit> + <RoundingMessageLocation>3</RoundingMessageLocation> + <CashFlowDataLocation>1</CashFlowDataLocation> + <FiscalYearEndMonth>11</FiscalYearEndMonth> + <ReportRange>0</ReportRange> + <ReportRangeFromDate>0</ReportRangeFromDate> + <ReportRangeToDate>0</ReportRangeToDate> + <TopMargin>0.3</TopMargin> + <BottomMargin>0.75</BottomMargin> + <LeftMargin>0.5</LeftMargin> + <RightMargin>1</RightMargin> + <AmortizationHeader></AmortizationHeader> + <ShowHeader>1</ShowHeader> + <HeaderAlignment>0</HeaderAlignment> + <AmortizationFooter></AmortizationFooter> + <ShowFooter>1</ShowFooter> + <FooterAlignment>0</FooterAlignment> + <HeaderTemplateA></HeaderTemplateA> + <HeaderTemplateAAlignment>0</HeaderTemplateAAlignment> + <HeaderTemplateB></HeaderTemplateB> + <HeaderTemplateBAlignment>0</HeaderTemplateBAlignment> + <FooterTemplateA></FooterTemplateA> + <FooterTemplateAAlignment>0</FooterTemplateAAlignment> + <FooterTemplateB></FooterTemplateB> + <FooterTemplateBAlignment>0</FooterTemplateBAlignment> + <AmortizationFont> + <FontType>0</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>1</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>2</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>3</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>4</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>5</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>6</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>7</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>8</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + <AmortizationFont> + <FontType>9</FontType> + <FontHeight>0</FontHeight> + <FontWidth>400</FontWidth> + <FontEscapement>0</FontEscapement> + <FontOrientation>0</FontOrientation> + <FontWeight>400</FontWeight> + <Italic>0</Italic> + <Underline>0</Underline> + <StrikeOut>0</StrikeOut> + <CharacterSet>0</CharacterSet> + <OutPrecision>0</OutPrecision> + <ClipPrecision>0</ClipPrecision> + <Quality>0</Quality> + <PitchAndFamily>0</PitchAndFamily> + <FontName>Arial</FontName> + <PointSizeTimes10>110</PointSizeTimes10> + <FontColor>0</FontColor> + </AmortizationFont> + </ReportOptions> + <Event> + <EventType>8</EventType> + <EventDate>05/08/2007</EventDate> + <EventAmount>2500000000</EventAmount> + <EventNumber>1</EventNumber> + </Event> + <Event> + <EventType>9</EventType> + <EventDate>06/08/2007</EventDate> + <EventAmount>23891300</EventAmount> + <EventNumber>180</EventNumber> + <EventPeriod>6</EventPeriod> + </Event> + <PointsAndFees> + <PointsPaidOnLoan>0.000000000000000</PointsPaidOnLoan> + <PrePaidInterestDays>0</PrePaidInterestDays> + <OtherCharges>0</OtherCharges> + </PointsAndFees> +</TValueCfm> + \ No newline at end of file diff --git a/test/fixtures/FEC_example_3_3_1.xml b/test/fixtures/FEC_example_3_3_1.xml new file mode 100644 index 0000000..bcb6d73 --- /dev/null +++ b/test/fixtures/FEC_example_3_3_1.xml @@ -0,0 +1,3575 @@ +<?xml version='1.0' encoding='windows-1252'?> +<TValueAmortizationSchedule> + <Rounding>1100</Rounding> + <Compounding>6</Compounding> + <NominalAnnualRate>0.08</NominalAnnualRate> + <APR>0.08</APR> + <FinanceCharge>1800434000</FinanceCharge> + <AmountFinanced>2500000000</AmountFinanced> + <TotalOfPayments>4300434000</TotalOfPayments> + <AmortizationLine> + <AmortizationLineType>8</AmortizationLineType> + <Date>05/08/2007</Date> + <Loan1Amount>2500000000</Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount></Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>0</InterestAccrued> + <InterestPaid>0</InterestPaid> + <PrincipalPaid>0</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2500000000</PrincipalBalance> + <TotalBalance>2500000000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2007</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16666700</InterestAccrued> + <InterestPaid>16666700</InterestPaid> + <PrincipalPaid>7224600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2492775400</PrincipalBalance> + <TotalBalance>2492775400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2007</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16618500</InterestAccrued> + <InterestPaid>16618500</InterestPaid> + <PrincipalPaid>7272800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2485502600</PrincipalBalance> + <TotalBalance>2485502600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2007</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16570000</InterestAccrued> + <InterestPaid>16570000</InterestPaid> + <PrincipalPaid>7321300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2478181300</PrincipalBalance> + <TotalBalance>2478181300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2007</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16521200</InterestAccrued> + <InterestPaid>16521200</InterestPaid> + <PrincipalPaid>7370100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2470811200</PrincipalBalance> + <TotalBalance>2470811200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2007</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16472100</InterestAccrued> + <InterestPaid>16472100</InterestPaid> + <PrincipalPaid>7419200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2463392000</PrincipalBalance> + <TotalBalance>2463392000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2007</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16422600</InterestAccrued> + <InterestPaid>16422600</InterestPaid> + <PrincipalPaid>7468700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2455923300</PrincipalBalance> + <TotalBalance>2455923300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2007</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16372800</InterestAccrued> + <InterestPaid>16372800</InterestPaid> + <PrincipalPaid>7518500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2448404800</PrincipalBalance> + <TotalBalance>2448404800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2007</Date> + <Loan1Amount>2500000000</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>167239100</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>115643900</InterestAccrued> + <InterestPaid>115643900</InterestPaid> + <PrincipalPaid>51595200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2448404800</PrincipalBalance> + <TotalBalance>2448404800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16322700</InterestAccrued> + <InterestPaid>16322700</InterestPaid> + <PrincipalPaid>7568600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2440836200</PrincipalBalance> + <TotalBalance>2440836200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16272200</InterestAccrued> + <InterestPaid>16272200</InterestPaid> + <PrincipalPaid>7619100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2433217100</PrincipalBalance> + <TotalBalance>2433217100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16221400</InterestAccrued> + <InterestPaid>16221400</InterestPaid> + <PrincipalPaid>7669900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2425547200</PrincipalBalance> + <TotalBalance>2425547200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16170300</InterestAccrued> + <InterestPaid>16170300</InterestPaid> + <PrincipalPaid>7721000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2417826200</PrincipalBalance> + <TotalBalance>2417826200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16118800</InterestAccrued> + <InterestPaid>16118800</InterestPaid> + <PrincipalPaid>7772500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2410053700</PrincipalBalance> + <TotalBalance>2410053700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16067000</InterestAccrued> + <InterestPaid>16067000</InterestPaid> + <PrincipalPaid>7824300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2402229400</PrincipalBalance> + <TotalBalance>2402229400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>16014900</InterestAccrued> + <InterestPaid>16014900</InterestPaid> + <PrincipalPaid>7876400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2394353000</PrincipalBalance> + <TotalBalance>2394353000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15962400</InterestAccrued> + <InterestPaid>15962400</InterestPaid> + <PrincipalPaid>7928900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2386424100</PrincipalBalance> + <TotalBalance>2386424100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15909500</InterestAccrued> + <InterestPaid>15909500</InterestPaid> + <PrincipalPaid>7981800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2378442300</PrincipalBalance> + <TotalBalance>2378442300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15856300</InterestAccrued> + <InterestPaid>15856300</InterestPaid> + <PrincipalPaid>8035000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2370407300</PrincipalBalance> + <TotalBalance>2370407300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15802700</InterestAccrued> + <InterestPaid>15802700</InterestPaid> + <PrincipalPaid>8088600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2362318700</PrincipalBalance> + <TotalBalance>2362318700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2008</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15748800</InterestAccrued> + <InterestPaid>15748800</InterestPaid> + <PrincipalPaid>8142500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2354176200</PrincipalBalance> + <TotalBalance>2354176200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2008</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>192467000</InterestAccrued> + <InterestPaid>192467000</InterestPaid> + <PrincipalPaid>94228600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2354176200</PrincipalBalance> + <TotalBalance>2354176200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15694500</InterestAccrued> + <InterestPaid>15694500</InterestPaid> + <PrincipalPaid>8196800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2345979400</PrincipalBalance> + <TotalBalance>2345979400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15639900</InterestAccrued> + <InterestPaid>15639900</InterestPaid> + <PrincipalPaid>8251400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2337728000</PrincipalBalance> + <TotalBalance>2337728000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15584900</InterestAccrued> + <InterestPaid>15584900</InterestPaid> + <PrincipalPaid>8306400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2329421600</PrincipalBalance> + <TotalBalance>2329421600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15529500</InterestAccrued> + <InterestPaid>15529500</InterestPaid> + <PrincipalPaid>8361800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2321059800</PrincipalBalance> + <TotalBalance>2321059800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15473700</InterestAccrued> + <InterestPaid>15473700</InterestPaid> + <PrincipalPaid>8417600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2312642200</PrincipalBalance> + <TotalBalance>2312642200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15417600</InterestAccrued> + <InterestPaid>15417600</InterestPaid> + <PrincipalPaid>8473700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2304168500</PrincipalBalance> + <TotalBalance>2304168500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15361100</InterestAccrued> + <InterestPaid>15361100</InterestPaid> + <PrincipalPaid>8530200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2295638300</PrincipalBalance> + <TotalBalance>2295638300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15304300</InterestAccrued> + <InterestPaid>15304300</InterestPaid> + <PrincipalPaid>8587000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2287051300</PrincipalBalance> + <TotalBalance>2287051300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15247000</InterestAccrued> + <InterestPaid>15247000</InterestPaid> + <PrincipalPaid>8644300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2278407000</PrincipalBalance> + <TotalBalance>2278407000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15189400</InterestAccrued> + <InterestPaid>15189400</InterestPaid> + <PrincipalPaid>8701900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2269705100</PrincipalBalance> + <TotalBalance>2269705100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15131400</InterestAccrued> + <InterestPaid>15131400</InterestPaid> + <PrincipalPaid>8759900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2260945200</PrincipalBalance> + <TotalBalance>2260945200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2009</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15073000</InterestAccrued> + <InterestPaid>15073000</InterestPaid> + <PrincipalPaid>8818300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2252126900</PrincipalBalance> + <TotalBalance>2252126900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2009</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>184646300</InterestAccrued> + <InterestPaid>184646300</InterestPaid> + <PrincipalPaid>102049300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2252126900</PrincipalBalance> + <TotalBalance>2252126900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>15014200</InterestAccrued> + <InterestPaid>15014200</InterestPaid> + <PrincipalPaid>8877100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2243249800</PrincipalBalance> + <TotalBalance>2243249800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14955000</InterestAccrued> + <InterestPaid>14955000</InterestPaid> + <PrincipalPaid>8936300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2234313500</PrincipalBalance> + <TotalBalance>2234313500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14895400</InterestAccrued> + <InterestPaid>14895400</InterestPaid> + <PrincipalPaid>8995900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2225317600</PrincipalBalance> + <TotalBalance>2225317600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14835500</InterestAccrued> + <InterestPaid>14835500</InterestPaid> + <PrincipalPaid>9055800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2216261800</PrincipalBalance> + <TotalBalance>2216261800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14775100</InterestAccrued> + <InterestPaid>14775100</InterestPaid> + <PrincipalPaid>9116200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2207145600</PrincipalBalance> + <TotalBalance>2207145600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14714300</InterestAccrued> + <InterestPaid>14714300</InterestPaid> + <PrincipalPaid>9177000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2197968600</PrincipalBalance> + <TotalBalance>2197968600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14653100</InterestAccrued> + <InterestPaid>14653100</InterestPaid> + <PrincipalPaid>9238200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2188730400</PrincipalBalance> + <TotalBalance>2188730400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14591500</InterestAccrued> + <InterestPaid>14591500</InterestPaid> + <PrincipalPaid>9299800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2179430600</PrincipalBalance> + <TotalBalance>2179430600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14529500</InterestAccrued> + <InterestPaid>14529500</InterestPaid> + <PrincipalPaid>9361800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2170068800</PrincipalBalance> + <TotalBalance>2170068800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14467100</InterestAccrued> + <InterestPaid>14467100</InterestPaid> + <PrincipalPaid>9424200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2160644600</PrincipalBalance> + <TotalBalance>2160644600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14404300</InterestAccrued> + <InterestPaid>14404300</InterestPaid> + <PrincipalPaid>9487000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2151157600</PrincipalBalance> + <TotalBalance>2151157600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2010</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14341100</InterestAccrued> + <InterestPaid>14341100</InterestPaid> + <PrincipalPaid>9550200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2141607400</PrincipalBalance> + <TotalBalance>2141607400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2010</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>176176100</InterestAccrued> + <InterestPaid>176176100</InterestPaid> + <PrincipalPaid>110519500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2141607400</PrincipalBalance> + <TotalBalance>2141607400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14277400</InterestAccrued> + <InterestPaid>14277400</InterestPaid> + <PrincipalPaid>9613900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2131993500</PrincipalBalance> + <TotalBalance>2131993500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14213300</InterestAccrued> + <InterestPaid>14213300</InterestPaid> + <PrincipalPaid>9678000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2122315500</PrincipalBalance> + <TotalBalance>2122315500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14148800</InterestAccrued> + <InterestPaid>14148800</InterestPaid> + <PrincipalPaid>9742500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2112573000</PrincipalBalance> + <TotalBalance>2112573000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14083800</InterestAccrued> + <InterestPaid>14083800</InterestPaid> + <PrincipalPaid>9807500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2102765500</PrincipalBalance> + <TotalBalance>2102765500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>14018400</InterestAccrued> + <InterestPaid>14018400</InterestPaid> + <PrincipalPaid>9872900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2092892600</PrincipalBalance> + <TotalBalance>2092892600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13952600</InterestAccrued> + <InterestPaid>13952600</InterestPaid> + <PrincipalPaid>9938700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2082953900</PrincipalBalance> + <TotalBalance>2082953900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13886400</InterestAccrued> + <InterestPaid>13886400</InterestPaid> + <PrincipalPaid>10004900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2072949000</PrincipalBalance> + <TotalBalance>2072949000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13819700</InterestAccrued> + <InterestPaid>13819700</InterestPaid> + <PrincipalPaid>10071600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2062877400</PrincipalBalance> + <TotalBalance>2062877400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13752500</InterestAccrued> + <InterestPaid>13752500</InterestPaid> + <PrincipalPaid>10138800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2052738600</PrincipalBalance> + <TotalBalance>2052738600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13684900</InterestAccrued> + <InterestPaid>13684900</InterestPaid> + <PrincipalPaid>10206400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2042532200</PrincipalBalance> + <TotalBalance>2042532200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13616900</InterestAccrued> + <InterestPaid>13616900</InterestPaid> + <PrincipalPaid>10274400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2032257800</PrincipalBalance> + <TotalBalance>2032257800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2011</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13548400</InterestAccrued> + <InterestPaid>13548400</InterestPaid> + <PrincipalPaid>10342900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2021914900</PrincipalBalance> + <TotalBalance>2021914900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2011</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>167003100</InterestAccrued> + <InterestPaid>167003100</InterestPaid> + <PrincipalPaid>119692500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2021914900</PrincipalBalance> + <TotalBalance>2021914900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13479400</InterestAccrued> + <InterestPaid>13479400</InterestPaid> + <PrincipalPaid>10411900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2011503000</PrincipalBalance> + <TotalBalance>2011503000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13410000</InterestAccrued> + <InterestPaid>13410000</InterestPaid> + <PrincipalPaid>10481300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>2001021700</PrincipalBalance> + <TotalBalance>2001021700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13340100</InterestAccrued> + <InterestPaid>13340100</InterestPaid> + <PrincipalPaid>10551200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1990470500</PrincipalBalance> + <TotalBalance>1990470500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13269800</InterestAccrued> + <InterestPaid>13269800</InterestPaid> + <PrincipalPaid>10621500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1979849000</PrincipalBalance> + <TotalBalance>1979849000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13199000</InterestAccrued> + <InterestPaid>13199000</InterestPaid> + <PrincipalPaid>10692300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1969156700</PrincipalBalance> + <TotalBalance>1969156700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13127700</InterestAccrued> + <InterestPaid>13127700</InterestPaid> + <PrincipalPaid>10763600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1958393100</PrincipalBalance> + <TotalBalance>1958393100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>13056000</InterestAccrued> + <InterestPaid>13056000</InterestPaid> + <PrincipalPaid>10835300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1947557800</PrincipalBalance> + <TotalBalance>1947557800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12983700</InterestAccrued> + <InterestPaid>12983700</InterestPaid> + <PrincipalPaid>10907600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1936650200</PrincipalBalance> + <TotalBalance>1936650200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12911000</InterestAccrued> + <InterestPaid>12911000</InterestPaid> + <PrincipalPaid>10980300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1925669900</PrincipalBalance> + <TotalBalance>1925669900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12837800</InterestAccrued> + <InterestPaid>12837800</InterestPaid> + <PrincipalPaid>11053500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1914616400</PrincipalBalance> + <TotalBalance>1914616400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12764100</InterestAccrued> + <InterestPaid>12764100</InterestPaid> + <PrincipalPaid>11127200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1903489200</PrincipalBalance> + <TotalBalance>1903489200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2012</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12689900</InterestAccrued> + <InterestPaid>12689900</InterestPaid> + <PrincipalPaid>11201400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1892287800</PrincipalBalance> + <TotalBalance>1892287800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2012</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>157068500</InterestAccrued> + <InterestPaid>157068500</InterestPaid> + <PrincipalPaid>129627100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1892287800</PrincipalBalance> + <TotalBalance>1892287800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12615300</InterestAccrued> + <InterestPaid>12615300</InterestPaid> + <PrincipalPaid>11276000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1881011800</PrincipalBalance> + <TotalBalance>1881011800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12540100</InterestAccrued> + <InterestPaid>12540100</InterestPaid> + <PrincipalPaid>11351200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1869660600</PrincipalBalance> + <TotalBalance>1869660600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12464400</InterestAccrued> + <InterestPaid>12464400</InterestPaid> + <PrincipalPaid>11426900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1858233700</PrincipalBalance> + <TotalBalance>1858233700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12388200</InterestAccrued> + <InterestPaid>12388200</InterestPaid> + <PrincipalPaid>11503100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1846730600</PrincipalBalance> + <TotalBalance>1846730600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12311500</InterestAccrued> + <InterestPaid>12311500</InterestPaid> + <PrincipalPaid>11579800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1835150800</PrincipalBalance> + <TotalBalance>1835150800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12234300</InterestAccrued> + <InterestPaid>12234300</InterestPaid> + <PrincipalPaid>11657000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1823493800</PrincipalBalance> + <TotalBalance>1823493800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12156600</InterestAccrued> + <InterestPaid>12156600</InterestPaid> + <PrincipalPaid>11734700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1811759100</PrincipalBalance> + <TotalBalance>1811759100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>12078400</InterestAccrued> + <InterestPaid>12078400</InterestPaid> + <PrincipalPaid>11812900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1799946200</PrincipalBalance> + <TotalBalance>1799946200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11999600</InterestAccrued> + <InterestPaid>11999600</InterestPaid> + <PrincipalPaid>11891700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1788054500</PrincipalBalance> + <TotalBalance>1788054500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11920400</InterestAccrued> + <InterestPaid>11920400</InterestPaid> + <PrincipalPaid>11970900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1776083600</PrincipalBalance> + <TotalBalance>1776083600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11840600</InterestAccrued> + <InterestPaid>11840600</InterestPaid> + <PrincipalPaid>12050700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1764032900</PrincipalBalance> + <TotalBalance>1764032900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2013</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11760200</InterestAccrued> + <InterestPaid>11760200</InterestPaid> + <PrincipalPaid>12131100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1751901800</PrincipalBalance> + <TotalBalance>1751901800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2013</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>146309600</InterestAccrued> + <InterestPaid>146309600</InterestPaid> + <PrincipalPaid>140386000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1751901800</PrincipalBalance> + <TotalBalance>1751901800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11679300</InterestAccrued> + <InterestPaid>11679300</InterestPaid> + <PrincipalPaid>12212000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1739689800</PrincipalBalance> + <TotalBalance>1739689800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11597900</InterestAccrued> + <InterestPaid>11597900</InterestPaid> + <PrincipalPaid>12293400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1727396400</PrincipalBalance> + <TotalBalance>1727396400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11516000</InterestAccrued> + <InterestPaid>11516000</InterestPaid> + <PrincipalPaid>12375300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1715021100</PrincipalBalance> + <TotalBalance>1715021100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11433500</InterestAccrued> + <InterestPaid>11433500</InterestPaid> + <PrincipalPaid>12457800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1702563300</PrincipalBalance> + <TotalBalance>1702563300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11350400</InterestAccrued> + <InterestPaid>11350400</InterestPaid> + <PrincipalPaid>12540900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1690022400</PrincipalBalance> + <TotalBalance>1690022400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11266800</InterestAccrued> + <InterestPaid>11266800</InterestPaid> + <PrincipalPaid>12624500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1677397900</PrincipalBalance> + <TotalBalance>1677397900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11182700</InterestAccrued> + <InterestPaid>11182700</InterestPaid> + <PrincipalPaid>12708600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1664689300</PrincipalBalance> + <TotalBalance>1664689300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11097900</InterestAccrued> + <InterestPaid>11097900</InterestPaid> + <PrincipalPaid>12793400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1651895900</PrincipalBalance> + <TotalBalance>1651895900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>11012600</InterestAccrued> + <InterestPaid>11012600</InterestPaid> + <PrincipalPaid>12878700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1639017200</PrincipalBalance> + <TotalBalance>1639017200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10926800</InterestAccrued> + <InterestPaid>10926800</InterestPaid> + <PrincipalPaid>12964500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1626052700</PrincipalBalance> + <TotalBalance>1626052700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10840400</InterestAccrued> + <InterestPaid>10840400</InterestPaid> + <PrincipalPaid>13050900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1613001800</PrincipalBalance> + <TotalBalance>1613001800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2014</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10753300</InterestAccrued> + <InterestPaid>10753300</InterestPaid> + <PrincipalPaid>13138000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1599863800</PrincipalBalance> + <TotalBalance>1599863800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2014</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>134657600</InterestAccrued> + <InterestPaid>134657600</InterestPaid> + <PrincipalPaid>152038000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1599863800</PrincipalBalance> + <TotalBalance>1599863800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10665800</InterestAccrued> + <InterestPaid>10665800</InterestPaid> + <PrincipalPaid>13225500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1586638300</PrincipalBalance> + <TotalBalance>1586638300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10577600</InterestAccrued> + <InterestPaid>10577600</InterestPaid> + <PrincipalPaid>13313700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1573324600</PrincipalBalance> + <TotalBalance>1573324600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10488800</InterestAccrued> + <InterestPaid>10488800</InterestPaid> + <PrincipalPaid>13402500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1559922100</PrincipalBalance> + <TotalBalance>1559922100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10399500</InterestAccrued> + <InterestPaid>10399500</InterestPaid> + <PrincipalPaid>13491800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1546430300</PrincipalBalance> + <TotalBalance>1546430300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10309500</InterestAccrued> + <InterestPaid>10309500</InterestPaid> + <PrincipalPaid>13581800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1532848500</PrincipalBalance> + <TotalBalance>1532848500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10219000</InterestAccrued> + <InterestPaid>10219000</InterestPaid> + <PrincipalPaid>13672300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1519176200</PrincipalBalance> + <TotalBalance>1519176200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10127800</InterestAccrued> + <InterestPaid>10127800</InterestPaid> + <PrincipalPaid>13763500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1505412700</PrincipalBalance> + <TotalBalance>1505412700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>10036100</InterestAccrued> + <InterestPaid>10036100</InterestPaid> + <PrincipalPaid>13855200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1491557500</PrincipalBalance> + <TotalBalance>1491557500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9943700</InterestAccrued> + <InterestPaid>9943700</InterestPaid> + <PrincipalPaid>13947600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1477609900</PrincipalBalance> + <TotalBalance>1477609900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9850700</InterestAccrued> + <InterestPaid>9850700</InterestPaid> + <PrincipalPaid>14040600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1463569300</PrincipalBalance> + <TotalBalance>1463569300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9757100</InterestAccrued> + <InterestPaid>9757100</InterestPaid> + <PrincipalPaid>14134200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1449435100</PrincipalBalance> + <TotalBalance>1449435100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2015</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9662900</InterestAccrued> + <InterestPaid>9662900</InterestPaid> + <PrincipalPaid>14228400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1435206700</PrincipalBalance> + <TotalBalance>1435206700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2015</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>122038500</InterestAccrued> + <InterestPaid>122038500</InterestPaid> + <PrincipalPaid>164657100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1435206700</PrincipalBalance> + <TotalBalance>1435206700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9568000</InterestAccrued> + <InterestPaid>9568000</InterestPaid> + <PrincipalPaid>14323300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1420883400</PrincipalBalance> + <TotalBalance>1420883400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9472600</InterestAccrued> + <InterestPaid>9472600</InterestPaid> + <PrincipalPaid>14418700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1406464700</PrincipalBalance> + <TotalBalance>1406464700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9376400</InterestAccrued> + <InterestPaid>9376400</InterestPaid> + <PrincipalPaid>14514900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1391949800</PrincipalBalance> + <TotalBalance>1391949800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9279700</InterestAccrued> + <InterestPaid>9279700</InterestPaid> + <PrincipalPaid>14611600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1377338200</PrincipalBalance> + <TotalBalance>1377338200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9182300</InterestAccrued> + <InterestPaid>9182300</InterestPaid> + <PrincipalPaid>14709000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1362629200</PrincipalBalance> + <TotalBalance>1362629200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>9084200</InterestAccrued> + <InterestPaid>9084200</InterestPaid> + <PrincipalPaid>14807100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1347822100</PrincipalBalance> + <TotalBalance>1347822100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8985500</InterestAccrued> + <InterestPaid>8985500</InterestPaid> + <PrincipalPaid>14905800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1332916300</PrincipalBalance> + <TotalBalance>1332916300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8886100</InterestAccrued> + <InterestPaid>8886100</InterestPaid> + <PrincipalPaid>15005200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1317911100</PrincipalBalance> + <TotalBalance>1317911100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8786100</InterestAccrued> + <InterestPaid>8786100</InterestPaid> + <PrincipalPaid>15105200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1302805900</PrincipalBalance> + <TotalBalance>1302805900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8685400</InterestAccrued> + <InterestPaid>8685400</InterestPaid> + <PrincipalPaid>15205900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1287600000</PrincipalBalance> + <TotalBalance>1287600000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8584000</InterestAccrued> + <InterestPaid>8584000</InterestPaid> + <PrincipalPaid>15307300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1272292700</PrincipalBalance> + <TotalBalance>1272292700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2016</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8482000</InterestAccrued> + <InterestPaid>8482000</InterestPaid> + <PrincipalPaid>15409300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1256883400</PrincipalBalance> + <TotalBalance>1256883400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2016</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>108372300</InterestAccrued> + <InterestPaid>108372300</InterestPaid> + <PrincipalPaid>178323300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1256883400</PrincipalBalance> + <TotalBalance>1256883400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8379200</InterestAccrued> + <InterestPaid>8379200</InterestPaid> + <PrincipalPaid>15512100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1241371300</PrincipalBalance> + <TotalBalance>1241371300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8275800</InterestAccrued> + <InterestPaid>8275800</InterestPaid> + <PrincipalPaid>15615500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1225755800</PrincipalBalance> + <TotalBalance>1225755800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8171700</InterestAccrued> + <InterestPaid>8171700</InterestPaid> + <PrincipalPaid>15719600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1210036200</PrincipalBalance> + <TotalBalance>1210036200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>8066900</InterestAccrued> + <InterestPaid>8066900</InterestPaid> + <PrincipalPaid>15824400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1194211800</PrincipalBalance> + <TotalBalance>1194211800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7961400</InterestAccrued> + <InterestPaid>7961400</InterestPaid> + <PrincipalPaid>15929900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1178281900</PrincipalBalance> + <TotalBalance>1178281900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7855200</InterestAccrued> + <InterestPaid>7855200</InterestPaid> + <PrincipalPaid>16036100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1162245800</PrincipalBalance> + <TotalBalance>1162245800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7748300</InterestAccrued> + <InterestPaid>7748300</InterestPaid> + <PrincipalPaid>16143000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1146102800</PrincipalBalance> + <TotalBalance>1146102800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7640700</InterestAccrued> + <InterestPaid>7640700</InterestPaid> + <PrincipalPaid>16250600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1129852200</PrincipalBalance> + <TotalBalance>1129852200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7532300</InterestAccrued> + <InterestPaid>7532300</InterestPaid> + <PrincipalPaid>16359000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1113493200</PrincipalBalance> + <TotalBalance>1113493200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7423300</InterestAccrued> + <InterestPaid>7423300</InterestPaid> + <PrincipalPaid>16468000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1097025200</PrincipalBalance> + <TotalBalance>1097025200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7313500</InterestAccrued> + <InterestPaid>7313500</InterestPaid> + <PrincipalPaid>16577800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1080447400</PrincipalBalance> + <TotalBalance>1080447400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2017</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7203000</InterestAccrued> + <InterestPaid>7203000</InterestPaid> + <PrincipalPaid>16688300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1063759100</PrincipalBalance> + <TotalBalance>1063759100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2017</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>93571300</InterestAccrued> + <InterestPaid>93571300</InterestPaid> + <PrincipalPaid>193124300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1063759100</PrincipalBalance> + <TotalBalance>1063759100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>7091700</InterestAccrued> + <InterestPaid>7091700</InterestPaid> + <PrincipalPaid>16799600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1046959500</PrincipalBalance> + <TotalBalance>1046959500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6979700</InterestAccrued> + <InterestPaid>6979700</InterestPaid> + <PrincipalPaid>16911600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1030047900</PrincipalBalance> + <TotalBalance>1030047900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6867000</InterestAccrued> + <InterestPaid>6867000</InterestPaid> + <PrincipalPaid>17024300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>1013023600</PrincipalBalance> + <TotalBalance>1013023600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6753500</InterestAccrued> + <InterestPaid>6753500</InterestPaid> + <PrincipalPaid>17137800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>995885800</PrincipalBalance> + <TotalBalance>995885800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6639200</InterestAccrued> + <InterestPaid>6639200</InterestPaid> + <PrincipalPaid>17252100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>978633700</PrincipalBalance> + <TotalBalance>978633700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6524200</InterestAccrued> + <InterestPaid>6524200</InterestPaid> + <PrincipalPaid>17367100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>961266600</PrincipalBalance> + <TotalBalance>961266600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6408400</InterestAccrued> + <InterestPaid>6408400</InterestPaid> + <PrincipalPaid>17482900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>943783700</PrincipalBalance> + <TotalBalance>943783700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6291900</InterestAccrued> + <InterestPaid>6291900</InterestPaid> + <PrincipalPaid>17599400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>926184300</PrincipalBalance> + <TotalBalance>926184300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6174600</InterestAccrued> + <InterestPaid>6174600</InterestPaid> + <PrincipalPaid>17716700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>908467600</PrincipalBalance> + <TotalBalance>908467600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>6056500</InterestAccrued> + <InterestPaid>6056500</InterestPaid> + <PrincipalPaid>17834800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>890632800</PrincipalBalance> + <TotalBalance>890632800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>5937600</InterestAccrued> + <InterestPaid>5937600</InterestPaid> + <PrincipalPaid>17953700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>872679100</PrincipalBalance> + <TotalBalance>872679100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2018</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>5817900</InterestAccrued> + <InterestPaid>5817900</InterestPaid> + <PrincipalPaid>18073400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>854605700</PrincipalBalance> + <TotalBalance>854605700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2018</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>77542200</InterestAccrued> + <InterestPaid>77542200</InterestPaid> + <PrincipalPaid>209153400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>854605700</PrincipalBalance> + <TotalBalance>854605700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>5697400</InterestAccrued> + <InterestPaid>5697400</InterestPaid> + <PrincipalPaid>18193900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>836411800</PrincipalBalance> + <TotalBalance>836411800</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>5576100</InterestAccrued> + <InterestPaid>5576100</InterestPaid> + <PrincipalPaid>18315200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>818096600</PrincipalBalance> + <TotalBalance>818096600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>5454000</InterestAccrued> + <InterestPaid>5454000</InterestPaid> + <PrincipalPaid>18437300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>799659300</PrincipalBalance> + <TotalBalance>799659300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>5331100</InterestAccrued> + <InterestPaid>5331100</InterestPaid> + <PrincipalPaid>18560200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>781099100</PrincipalBalance> + <TotalBalance>781099100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>5207300</InterestAccrued> + <InterestPaid>5207300</InterestPaid> + <PrincipalPaid>18684000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>762415100</PrincipalBalance> + <TotalBalance>762415100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>5082800</InterestAccrued> + <InterestPaid>5082800</InterestPaid> + <PrincipalPaid>18808500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>743606600</PrincipalBalance> + <TotalBalance>743606600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>4957400</InterestAccrued> + <InterestPaid>4957400</InterestPaid> + <PrincipalPaid>18933900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>724672700</PrincipalBalance> + <TotalBalance>724672700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>4831200</InterestAccrued> + <InterestPaid>4831200</InterestPaid> + <PrincipalPaid>19060100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>705612600</PrincipalBalance> + <TotalBalance>705612600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>4704100</InterestAccrued> + <InterestPaid>4704100</InterestPaid> + <PrincipalPaid>19187200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>686425400</PrincipalBalance> + <TotalBalance>686425400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>4576200</InterestAccrued> + <InterestPaid>4576200</InterestPaid> + <PrincipalPaid>19315100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>667110300</PrincipalBalance> + <TotalBalance>667110300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>4447400</InterestAccrued> + <InterestPaid>4447400</InterestPaid> + <PrincipalPaid>19443900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>647666400</PrincipalBalance> + <TotalBalance>647666400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2019</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>4317800</InterestAccrued> + <InterestPaid>4317800</InterestPaid> + <PrincipalPaid>19573500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>628092900</PrincipalBalance> + <TotalBalance>628092900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2019</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>60182800</InterestAccrued> + <InterestPaid>60182800</InterestPaid> + <PrincipalPaid>226512800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>628092900</PrincipalBalance> + <TotalBalance>628092900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>4187300</InterestAccrued> + <InterestPaid>4187300</InterestPaid> + <PrincipalPaid>19704000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>608388900</PrincipalBalance> + <TotalBalance>608388900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>4055900</InterestAccrued> + <InterestPaid>4055900</InterestPaid> + <PrincipalPaid>19835400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>588553500</PrincipalBalance> + <TotalBalance>588553500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>3923700</InterestAccrued> + <InterestPaid>3923700</InterestPaid> + <PrincipalPaid>19967600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>568585900</PrincipalBalance> + <TotalBalance>568585900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>3790600</InterestAccrued> + <InterestPaid>3790600</InterestPaid> + <PrincipalPaid>20100700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>548485200</PrincipalBalance> + <TotalBalance>548485200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>3656600</InterestAccrued> + <InterestPaid>3656600</InterestPaid> + <PrincipalPaid>20234700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>528250500</PrincipalBalance> + <TotalBalance>528250500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>3521700</InterestAccrued> + <InterestPaid>3521700</InterestPaid> + <PrincipalPaid>20369600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>507880900</PrincipalBalance> + <TotalBalance>507880900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>3385900</InterestAccrued> + <InterestPaid>3385900</InterestPaid> + <PrincipalPaid>20505400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>487375500</PrincipalBalance> + <TotalBalance>487375500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>3249200</InterestAccrued> + <InterestPaid>3249200</InterestPaid> + <PrincipalPaid>20642100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>466733400</PrincipalBalance> + <TotalBalance>466733400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>3111600</InterestAccrued> + <InterestPaid>3111600</InterestPaid> + <PrincipalPaid>20779700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>445953700</PrincipalBalance> + <TotalBalance>445953700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>2973000</InterestAccrued> + <InterestPaid>2973000</InterestPaid> + <PrincipalPaid>20918300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>425035400</PrincipalBalance> + <TotalBalance>425035400</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>2833600</InterestAccrued> + <InterestPaid>2833600</InterestPaid> + <PrincipalPaid>21057700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>403977700</PrincipalBalance> + <TotalBalance>403977700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2020</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>2693200</InterestAccrued> + <InterestPaid>2693200</InterestPaid> + <PrincipalPaid>21198100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>382779600</PrincipalBalance> + <TotalBalance>382779600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2020</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>41382300</InterestAccrued> + <InterestPaid>41382300</InterestPaid> + <PrincipalPaid>245313300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>382779600</PrincipalBalance> + <TotalBalance>382779600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>2551900</InterestAccrued> + <InterestPaid>2551900</InterestPaid> + <PrincipalPaid>21339400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>361440200</PrincipalBalance> + <TotalBalance>361440200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>2409600</InterestAccrued> + <InterestPaid>2409600</InterestPaid> + <PrincipalPaid>21481700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>339958500</PrincipalBalance> + <TotalBalance>339958500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>2266400</InterestAccrued> + <InterestPaid>2266400</InterestPaid> + <PrincipalPaid>21624900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>318333600</PrincipalBalance> + <TotalBalance>318333600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>2122200</InterestAccrued> + <InterestPaid>2122200</InterestPaid> + <PrincipalPaid>21769100</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>296564500</PrincipalBalance> + <TotalBalance>296564500</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>1977100</InterestAccrued> + <InterestPaid>1977100</InterestPaid> + <PrincipalPaid>21914200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>274650300</PrincipalBalance> + <TotalBalance>274650300</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>06/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>1831000</InterestAccrued> + <InterestPaid>1831000</InterestPaid> + <PrincipalPaid>22060300</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>252590000</PrincipalBalance> + <TotalBalance>252590000</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>07/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>1683900</InterestAccrued> + <InterestPaid>1683900</InterestPaid> + <PrincipalPaid>22207400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>230382600</PrincipalBalance> + <TotalBalance>230382600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>08/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>1535900</InterestAccrued> + <InterestPaid>1535900</InterestPaid> + <PrincipalPaid>22355400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>208027200</PrincipalBalance> + <TotalBalance>208027200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>09/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>1386800</InterestAccrued> + <InterestPaid>1386800</InterestPaid> + <PrincipalPaid>22504500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>185522700</PrincipalBalance> + <TotalBalance>185522700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>10/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>1236800</InterestAccrued> + <InterestPaid>1236800</InterestPaid> + <PrincipalPaid>22654500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>162868200</PrincipalBalance> + <TotalBalance>162868200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>11/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>1085800</InterestAccrued> + <InterestPaid>1085800</InterestPaid> + <PrincipalPaid>22805500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>140062700</PrincipalBalance> + <TotalBalance>140062700</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>12/08/2021</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>933800</InterestAccrued> + <InterestPaid>933800</InterestPaid> + <PrincipalPaid>22957500</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>117105200</PrincipalBalance> + <TotalBalance>117105200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2021</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>286695600</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>21021200</InterestAccrued> + <InterestPaid>21021200</InterestPaid> + <PrincipalPaid>265674400</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>117105200</PrincipalBalance> + <TotalBalance>117105200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>01/08/2022</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>780700</InterestAccrued> + <InterestPaid>780700</InterestPaid> + <PrincipalPaid>23110600</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>93994600</PrincipalBalance> + <TotalBalance>93994600</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>02/08/2022</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>626600</InterestAccrued> + <InterestPaid>626600</InterestPaid> + <PrincipalPaid>23264700</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>70729900</PrincipalBalance> + <TotalBalance>70729900</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>03/08/2022</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>471500</InterestAccrued> + <InterestPaid>471500</InterestPaid> + <PrincipalPaid>23419800</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>47310100</PrincipalBalance> + <TotalBalance>47310100</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>04/08/2022</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>315400</InterestAccrued> + <InterestPaid>315400</InterestPaid> + <PrincipalPaid>23575900</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>23734200</PrincipalBalance> + <TotalBalance>23734200</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>9</AmortizationLineType> + <Date>05/08/2022</Date> + <Loan1Amount></Loan1Amount> + <Loan2Amount></Loan2Amount> + <Loan3Amount></Loan3Amount> + <Payment1Amount>23891300</Payment1Amount> + <Payment2Amount></Payment2Amount> + <Payment3Amount></Payment3Amount> + <InterestAccrued>157100</InterestAccrued> + <InterestPaid>157100</InterestPaid> + <PrincipalPaid>23734200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>0</PrincipalBalance> + <TotalBalance>0</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>51</AmortizationLineType> + <Date>12/31/2022</Date> + <Loan1Amount>0</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>119456500</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>2351300</InterestAccrued> + <InterestPaid>2351300</InterestPaid> + <PrincipalPaid>117105200</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>0</PrincipalBalance> + <TotalBalance>0</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> + <AmortizationLine> + <AmortizationLineType>52</AmortizationLineType> + <Date>05/31/2022</Date> + <Loan1Amount>2500000000</Loan1Amount> + <Loan2Amount>0</Loan2Amount> + <Loan3Amount>0</Loan3Amount> + <Payment1Amount>4300434000</Payment1Amount> + <Payment2Amount>0</Payment2Amount> + <Payment3Amount>0</Payment3Amount> + <InterestAccrued>1800434000</InterestAccrued> + <InterestPaid>1800434000</InterestPaid> + <PrincipalPaid>2500000000</PrincipalPaid> + <UnpaidInterestBalance>0</UnpaidInterestBalance> + <PrincipalBalance>0</PrincipalBalance> + <TotalBalance>0</TotalBalance> + <RateChangeRate></RateChangeRate> + <RateChangeCompounding>13</RateChangeCompounding> + </AmortizationLine> +</TValueAmortizationSchedule> + \ No newline at end of file diff --git a/test/unit/amortization_test.rb b/test/unit/amortization_test.rb index 84fd7c5..72cfd85 100644 --- a/test/unit/amortization_test.rb +++ b/test/unit/amortization_test.rb @@ -1,9 +1,31 @@ require File.dirname(__FILE__) + '/../test_helper' class Stater::AmortizationTest < Test::Unit::TestCase - def test_payment_amount - assert_equal '26.38', Stater::Amortization.payment_amount(100.00, 0.10, 5).to_s + def test_new_amortization + amortization = Stater::Amortization.new + # assert_equal [], amortization.schedule + assert_nil amortization.principal + assert_nil amortization.periodic_rate + assert_nil amortization.periods + end + + def test_payment + principal = 250000.00 + periodic_rate = 0.08 / 12 + periods = 15 * 12 + + amortization = Stater::Amortization.new(250000.00, periodic_rate, periods) + assert_equal '2389.13', amortization.payment.to_s + end + + def test_schedule + principal = 250000.00 + periodic_rate = 0.08 / 12 + periods = 15 * 12 + + amortization = Stater::Amortization.new(250000.00, periodic_rate, periods) + # assert_equal '', amortization.schedule end end \ No newline at end of file diff --git a/test/unit/tvm_test.rb b/test/unit/tvm_test.rb index 79ad65f..ec656d6 100644 --- a/test/unit/tvm_test.rb +++ b/test/unit/tvm_test.rb @@ -1,37 +1,45 @@ require File.dirname(__FILE__) + '/../test_helper' class Stater::TVMTest < Test::Unit::TestCase def test_future_value - assert_equal '7935.08318331367', Stater::TVM.fv(6000.00, 0.04, 7, 12).to_s + present_value = 6000.00 + periodic_rate = 0.04 / 12 + periods = 84 + + assert_equal '7935.08318331367', Stater::TVM.fv(present_value, periodic_rate, periods).to_s end def test_present_value - assert_equal '5999.99759298276', Stater::TVM.pv(7935.08, 0.04, 7, 12).to_s + future_value = 7935.08 + periodic_rate = 0.04 / 12 + periods = 84 + + assert_equal '5999.99759298276', Stater::TVM.pv(future_value, periodic_rate, periods).to_s end def test_interest assert_equal '0.039999942499020946229393302929', sprintf('%3.30f', Stater::TVM.interest(6000.0, 7935.08, 7, 12)) end def test_years assert_equal '6.99998995405338', Stater::TVM.years(6000.0, 7935.08, 0.04, 12).to_s end def test_interest_to_apr assert_equal '0.195618171461533', Stater::TVM.i_to_apr(0.18, 12).to_s end def test_apr_to_interest assert_equal '0.179999854440594', Stater::TVM.apr_to_i(0.195618, 12).to_s end def test_apr_to_ear assert_equal '0.137919903125943', Stater::TVM.apr_to_ear(0.1299, 12).to_s end def test_ear_to_apr assert_equal '0.129900000000001', Stater::TVM.ear_to_apr(0.137919903125943, 12).to_s end end \ No newline at end of file
infused/stater
d5445318836ef9d64d35bc3b82554b4fed67b2b8
Simplify
diff --git a/lib/stater.rb b/lib/stater.rb index 3e19aa6..88e3598 100644 --- a/lib/stater.rb +++ b/lib/stater.rb @@ -1,7 +1,5 @@ require 'bigdecimal' +require 'stater/tvm' require 'stater/base' require 'stater/amortization' -require 'stater/simple_interest' -require 'stater/tvm/annual' -require 'stater/tvm/compound' diff --git a/lib/stater/simple_interest.rb b/lib/stater/simple_interest.rb deleted file mode 100644 index 47e9d65..0000000 --- a/lib/stater/simple_interest.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Stater - class SimpleInterest - class << self - def future_value(present_value, years, interest) - present_value * (1 + years * interest) - end - - alias_method :amount, :future_value - - def present_value(future_value, years, interest) - future_value / (1 + years * interest) - end - - alias_method :principal, :present_value - - def interest(present_value, future_value, years) - ((future_value / present_value ) - 1) / years - end - - def years(present_value, future_value, interest) - ((future_value / present_value) - 1) / interest - end - end - end -end diff --git a/lib/stater/tvm.rb b/lib/stater/tvm.rb new file mode 100644 index 0000000..f503856 --- /dev/null +++ b/lib/stater/tvm.rb @@ -0,0 +1,78 @@ +module Stater + class TVM + include Math + + class << self + # Calculates the future value + # pv = present value + # r = nominal interest rate + # y = years + # n = periods per year + def fv(pv, r, y, n) + pv * ((1 + (r / n))**(y * n)) + end + + # Calulates the present value + # fv = future value + # r = nominal interest rate + # y = years + # n = periods per year + def pv(fv, r, y, n) + fv / ((1 + (r / n))**(y * n)) + end + + # Calculates the nomical interest rate + # pv = present value + # fv = future value + # y = years + # n = compounding periods per year + def i(pv, fv, y, n) + n * ((fv / pv) ** (1 / (y.to_f * n)) - 1) + end + + # Calculates the number of years + # pv = present value + # fv = future value + # r = nominal interest rate + # n = compounding periods per year + def y(pv, fv, r, n) + Math.log(fv / pv) / (n * Math.log(1 + (r / n))) + end + + # Converts the nomical interest rate to APR (annual percentage rate) + # r = nominal interest rate + # n = compounding periods per year + def i_to_apr(r, n) + ((1 + (r / n)) ** n) - 1 + end + + # Converts APR (annual percentage rate) to the nomical interest rate + # apr = annual percentage rate + # n = compounding periods per year + def apr_to_i(apr, n) + n * ((1 + apr) ** (1/n.to_f) - 1) + end + + # Converts EAR (effective annual rate) to APR (annual percentage rate) + # apr = annual percentage rate + # n = compounding periods per year + def apr_to_ear(apr, n) + ((1 + apr / n)**n) - 1 + end + + # Converts APR (annual percentage rate) to EAR (effective annual rate) + # ear = effective annual rate + # n = compounding periods per year + def ear_to_apr(ear, n) + n * ((1 + ear)**(1 / n.to_f) - 1) + end + + alias_method :present_value, :pv + alias_method :future_value, :fv + alias_method :interest, :i + alias_method :years, :y + alias_method :annual_interest_to_apr, :i_to_apr + alias_method :apr_to_annual_interest, :apr_to_i + end + end +end \ No newline at end of file diff --git a/lib/stater/tvm/annual.rb b/lib/stater/tvm/annual.rb deleted file mode 100644 index 6e6ef56..0000000 --- a/lib/stater/tvm/annual.rb +++ /dev/null @@ -1,27 +0,0 @@ -module Stater - module TVM - module Annual - - # Present value of a future sum - # - # The present value formula is the core formula for the time value of money; each of the other formulae is derived from this - # formula. For example, the annuity formula is the sum of a series of present value calculations. The present value (PV) formula - # has four variables, each of which can be solved for: - # pv is the value at time = 0 - # fv is the value at time = n - # r is the rate at which the amount will be compounded each period - # n is the number of periods - def pv(fv, r, n) - fv / (1 + r)**n - end - - # Future value of a present sum - def fv(pv, r, n) - pv * (1 + r)**n - end - - # Present value of an annuity - - end - end -end \ No newline at end of file diff --git a/lib/stater/tvm/compound.rb b/lib/stater/tvm/compound.rb deleted file mode 100644 index 1d6cca5..0000000 --- a/lib/stater/tvm/compound.rb +++ /dev/null @@ -1,40 +0,0 @@ -module Stater::TVM - class Compound - class << self - # Calculates the future value given pv = present value, r = annual rate, y = years, n = periods per year - def fv(pv, r, y, n) - pv * ((1 + (r / n))**(y * n)) - end - - # Calulates the present value given fv = future value, r = annual rate, y = years, n = periods per year - def pv(fv, r, y, n) - fv / ((1 + (r / n))**(y * n)) - end - - # Calculates the interest given pv = present value, fv = future value, y = years, n = periods per year - def i(pv, fv, y, n) - n * ((fv / pv) ** (1 / (y.to_f * n)) - 1) - end - - # Calculates the number of years given the pv = present value, fv = future value, r = annual interest, n = periods per year - def y(pv, fv, r, n) - Math.log(fv / pv) / (n * Math.log(1 + (r / n))) - end - - def i_to_apr(r, n) - ((1 + (r / n)) ** n) - 1 - end - - def apr_to_i(apr, n) - n * ((1 + apr) ** (1/n.to_f) - 1) - end - - alias_method :present_value, :pv - alias_method :future_value, :fv - alias_method :interest, :i - alias_method :years, :y - alias_method :annual_interest_to_apr, :i_to_apr - alias_method :apr_to_annual_interest, :apr_to_i - end - end -end \ No newline at end of file diff --git a/test/unit/simple_interest_test.rb b/test/unit/simple_interest_test.rb deleted file mode 100644 index a25976d..0000000 --- a/test/unit/simple_interest_test.rb +++ /dev/null @@ -1,21 +0,0 @@ -require File.dirname(__FILE__) + '/../test_helper' - -class Stater::SimpleInterestTest < Test::Unit::TestCase - - def test_future_value - assert_equal '7680.0', Stater::SimpleInterest.future_value(6000.00, 7, 0.04).to_s - end - - def test_present_value - assert_equal '6000.0', Stater::SimpleInterest.present_value(7680.00, 7, 0.04).to_s - end - - def test_interest - assert_equal '0.04', Stater::SimpleInterest.interest(6000.00, 7680.00, 7).to_s - end - - def test_years - assert_equal '7.0', Stater::SimpleInterest.years(6000.00, 7680.00, 0.04).to_s - end - -end diff --git a/test/unit/tvm/annual_test.rb b/test/unit/tvm/annual_test.rb deleted file mode 100644 index c0aed24..0000000 --- a/test/unit/tvm/annual_test.rb +++ /dev/null @@ -1,30 +0,0 @@ -require File.dirname(__FILE__) + '/../../test_helper' - -class Stater::TVM::AnnualTest < Test::Unit::TestCase - include Stater::TVM::Annual - - def test_fv - assert_equal '99.9915', fv(95.23, 0.05, 1).to_s - end - - def test_pv - assert_equal '95.2380952380952', pv(100.00, 0.05, 1).to_s - end - - # def test_interest - # assert_equal '0.039999942499020946229393302929', sprintf('%3.30f', Stater::CompoundInterest.interest(6000.0, 7935.08, 7, 12)) - # end - # - # def test_years - # assert_equal '6.99998995405338', Stater::CompoundInterest.years(6000.0, 7935.08, 0.04, 12).to_s - # end - # - # def test_interest_to_apr - # assert_equal '0.195618171461533', Stater::CompoundInterest.interest_to_apr(0.18, 12).to_s - # end - # - # def test_apr_to_interest - # assert_equal '0.179999854440594', Stater::CompoundInterest.apr_to_interest(0.195618, 12).to_s - # end - -end \ No newline at end of file diff --git a/test/unit/tvm/compound_test.rb b/test/unit/tvm/compound_test.rb deleted file mode 100644 index e2c324d..0000000 --- a/test/unit/tvm/compound_test.rb +++ /dev/null @@ -1,29 +0,0 @@ -require File.dirname(__FILE__) + '/../../test_helper' - -class Stater::TVM::CompoundTest < Test::Unit::TestCase - - def test_future_value - assert_equal '7935.08318331367', Stater::TVM::Compound.fv(6000.00, 0.04, 7, 12).to_s - end - - def test_present_value - assert_equal '5999.99759298276', Stater::TVM::Compound.pv(7935.08, 0.04, 7, 12).to_s - end - - def test_interest - assert_equal '0.039999942499020946229393302929', sprintf('%3.30f', Stater::TVM::Compound.interest(6000.0, 7935.08, 7, 12)) - end - - def test_years - assert_equal '6.99998995405338', Stater::TVM::Compound.years(6000.0, 7935.08, 0.04, 12).to_s - end - - def test_interest_to_apr - assert_equal '0.195618171461533', Stater::TVM::Compound.i_to_apr(0.18, 12).to_s - end - - def test_apr_to_interest - assert_equal '0.179999854440594', Stater::TVM::Compound.apr_to_i(0.195618, 12).to_s - end - -end \ No newline at end of file diff --git a/test/unit/tvm_test.rb b/test/unit/tvm_test.rb new file mode 100644 index 0000000..79ad65f --- /dev/null +++ b/test/unit/tvm_test.rb @@ -0,0 +1,37 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class Stater::TVMTest < Test::Unit::TestCase + + def test_future_value + assert_equal '7935.08318331367', Stater::TVM.fv(6000.00, 0.04, 7, 12).to_s + end + + def test_present_value + assert_equal '5999.99759298276', Stater::TVM.pv(7935.08, 0.04, 7, 12).to_s + end + + def test_interest + assert_equal '0.039999942499020946229393302929', sprintf('%3.30f', Stater::TVM.interest(6000.0, 7935.08, 7, 12)) + end + + def test_years + assert_equal '6.99998995405338', Stater::TVM.years(6000.0, 7935.08, 0.04, 12).to_s + end + + def test_interest_to_apr + assert_equal '0.195618171461533', Stater::TVM.i_to_apr(0.18, 12).to_s + end + + def test_apr_to_interest + assert_equal '0.179999854440594', Stater::TVM.apr_to_i(0.195618, 12).to_s + end + + def test_apr_to_ear + assert_equal '0.137919903125943', Stater::TVM.apr_to_ear(0.1299, 12).to_s + end + + def test_ear_to_apr + assert_equal '0.129900000000001', Stater::TVM.ear_to_apr(0.137919903125943, 12).to_s + end + +end \ No newline at end of file
infused/stater
25ab5e49febab852223a1dd2134541ec506139e6
Move Manifest.txt to trunk
diff --git a/Manifest.txt b/Manifest.txt new file mode 100644 index 0000000..e69de29
infused/stater
d2611ed77f8b0f3e02a17e577cc9f5eb238ef325
Move Rakefile to trunk
diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..5f417b1 --- /dev/null +++ b/Rakefile @@ -0,0 +1,7 @@ +require "rubygems" +require "hoe" + +Hoe.new("stater", "1.0.0") do |p| + p.author = "Keith Morrison" + p.test_globs = ["test/**/*_test.rb"] +end
infused/stater
2cc7e6089e4128c62426acf5d5fc3b736ed88c2d
Move test to trunk
diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..f92e404 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,3 @@ +$:.unshift(File.dirname(__FILE__) + "/../lib/") +require 'test/unit' +require 'stater' diff --git a/test/unit/amortization_test.rb b/test/unit/amortization_test.rb new file mode 100644 index 0000000..84fd7c5 --- /dev/null +++ b/test/unit/amortization_test.rb @@ -0,0 +1,9 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class Stater::AmortizationTest < Test::Unit::TestCase + + def test_payment_amount + assert_equal '26.38', Stater::Amortization.payment_amount(100.00, 0.10, 5).to_s + end + +end \ No newline at end of file diff --git a/test/unit/base_test.rb b/test/unit/base_test.rb new file mode 100644 index 0000000..b826a05 --- /dev/null +++ b/test/unit/base_test.rb @@ -0,0 +1,9 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class Stater::BaseTest < Test::Unit::TestCase + + def test_sum_consecutive_integers + assert_equal 300, Stater::Base.sum_consecutive_integers(24) + end + +end \ No newline at end of file diff --git a/test/unit/simple_interest_test.rb b/test/unit/simple_interest_test.rb new file mode 100644 index 0000000..a25976d --- /dev/null +++ b/test/unit/simple_interest_test.rb @@ -0,0 +1,21 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class Stater::SimpleInterestTest < Test::Unit::TestCase + + def test_future_value + assert_equal '7680.0', Stater::SimpleInterest.future_value(6000.00, 7, 0.04).to_s + end + + def test_present_value + assert_equal '6000.0', Stater::SimpleInterest.present_value(7680.00, 7, 0.04).to_s + end + + def test_interest + assert_equal '0.04', Stater::SimpleInterest.interest(6000.00, 7680.00, 7).to_s + end + + def test_years + assert_equal '7.0', Stater::SimpleInterest.years(6000.00, 7680.00, 0.04).to_s + end + +end diff --git a/test/unit/tvm/annual_test.rb b/test/unit/tvm/annual_test.rb new file mode 100644 index 0000000..c0aed24 --- /dev/null +++ b/test/unit/tvm/annual_test.rb @@ -0,0 +1,30 @@ +require File.dirname(__FILE__) + '/../../test_helper' + +class Stater::TVM::AnnualTest < Test::Unit::TestCase + include Stater::TVM::Annual + + def test_fv + assert_equal '99.9915', fv(95.23, 0.05, 1).to_s + end + + def test_pv + assert_equal '95.2380952380952', pv(100.00, 0.05, 1).to_s + end + + # def test_interest + # assert_equal '0.039999942499020946229393302929', sprintf('%3.30f', Stater::CompoundInterest.interest(6000.0, 7935.08, 7, 12)) + # end + # + # def test_years + # assert_equal '6.99998995405338', Stater::CompoundInterest.years(6000.0, 7935.08, 0.04, 12).to_s + # end + # + # def test_interest_to_apr + # assert_equal '0.195618171461533', Stater::CompoundInterest.interest_to_apr(0.18, 12).to_s + # end + # + # def test_apr_to_interest + # assert_equal '0.179999854440594', Stater::CompoundInterest.apr_to_interest(0.195618, 12).to_s + # end + +end \ No newline at end of file diff --git a/test/unit/tvm/compound_test.rb b/test/unit/tvm/compound_test.rb new file mode 100644 index 0000000..e2c324d --- /dev/null +++ b/test/unit/tvm/compound_test.rb @@ -0,0 +1,29 @@ +require File.dirname(__FILE__) + '/../../test_helper' + +class Stater::TVM::CompoundTest < Test::Unit::TestCase + + def test_future_value + assert_equal '7935.08318331367', Stater::TVM::Compound.fv(6000.00, 0.04, 7, 12).to_s + end + + def test_present_value + assert_equal '5999.99759298276', Stater::TVM::Compound.pv(7935.08, 0.04, 7, 12).to_s + end + + def test_interest + assert_equal '0.039999942499020946229393302929', sprintf('%3.30f', Stater::TVM::Compound.interest(6000.0, 7935.08, 7, 12)) + end + + def test_years + assert_equal '6.99998995405338', Stater::TVM::Compound.years(6000.0, 7935.08, 0.04, 12).to_s + end + + def test_interest_to_apr + assert_equal '0.195618171461533', Stater::TVM::Compound.i_to_apr(0.18, 12).to_s + end + + def test_apr_to_interest + assert_equal '0.179999854440594', Stater::TVM::Compound.apr_to_i(0.195618, 12).to_s + end + +end \ No newline at end of file
infused/stater
d1e4a6361d2a63c617f530d639e3d9f003203b4b
Move lib to trunk
diff --git a/lib/stater.rb b/lib/stater.rb new file mode 100644 index 0000000..3e19aa6 --- /dev/null +++ b/lib/stater.rb @@ -0,0 +1,7 @@ +require 'bigdecimal' + +require 'stater/base' +require 'stater/amortization' +require 'stater/simple_interest' +require 'stater/tvm/annual' +require 'stater/tvm/compound' diff --git a/lib/stater/amortization.rb b/lib/stater/amortization.rb new file mode 100644 index 0000000..047c74e --- /dev/null +++ b/lib/stater/amortization.rb @@ -0,0 +1,24 @@ +module Stater + class Amortization + + class << self + # Calculates the payment when given the principal amount and interest rate + def payment_amount(principal_amount, interest_rate, number_of_payments) + x = interest_rate * principal_amount * ((1 + interest_rate) ** number_of_payments) + y = ((1 + interest_rate) ** number_of_payments) - 1 + return BigDecimal((x / y).to_s).round(2).to_f + end + + # Calculates the principal when given the periodic payment and interest rate + def principal(payment_amount, interest_rate, number_of_payments) + + end + + # Calculates the annual interest rate when given the principal amount and periodic payment + def interest(principal_amount, payment_amount, number_of_payments) + + end + end + + end +end \ No newline at end of file diff --git a/lib/stater/base.rb b/lib/stater/base.rb new file mode 100644 index 0000000..264c7f8 --- /dev/null +++ b/lib/stater/base.rb @@ -0,0 +1,9 @@ +module Stater + class Base + class << self + def sum_consecutive_integers(n) + (n**2 + n) / 2 + end + end + end +end diff --git a/lib/stater/simple_interest.rb b/lib/stater/simple_interest.rb new file mode 100644 index 0000000..47e9d65 --- /dev/null +++ b/lib/stater/simple_interest.rb @@ -0,0 +1,25 @@ +module Stater + class SimpleInterest + class << self + def future_value(present_value, years, interest) + present_value * (1 + years * interest) + end + + alias_method :amount, :future_value + + def present_value(future_value, years, interest) + future_value / (1 + years * interest) + end + + alias_method :principal, :present_value + + def interest(present_value, future_value, years) + ((future_value / present_value ) - 1) / years + end + + def years(present_value, future_value, interest) + ((future_value / present_value) - 1) / interest + end + end + end +end diff --git a/lib/stater/tvm/annual.rb b/lib/stater/tvm/annual.rb new file mode 100644 index 0000000..6e6ef56 --- /dev/null +++ b/lib/stater/tvm/annual.rb @@ -0,0 +1,27 @@ +module Stater + module TVM + module Annual + + # Present value of a future sum + # + # The present value formula is the core formula for the time value of money; each of the other formulae is derived from this + # formula. For example, the annuity formula is the sum of a series of present value calculations. The present value (PV) formula + # has four variables, each of which can be solved for: + # pv is the value at time = 0 + # fv is the value at time = n + # r is the rate at which the amount will be compounded each period + # n is the number of periods + def pv(fv, r, n) + fv / (1 + r)**n + end + + # Future value of a present sum + def fv(pv, r, n) + pv * (1 + r)**n + end + + # Present value of an annuity + + end + end +end \ No newline at end of file diff --git a/lib/stater/tvm/compound.rb b/lib/stater/tvm/compound.rb new file mode 100644 index 0000000..1d6cca5 --- /dev/null +++ b/lib/stater/tvm/compound.rb @@ -0,0 +1,40 @@ +module Stater::TVM + class Compound + class << self + # Calculates the future value given pv = present value, r = annual rate, y = years, n = periods per year + def fv(pv, r, y, n) + pv * ((1 + (r / n))**(y * n)) + end + + # Calulates the present value given fv = future value, r = annual rate, y = years, n = periods per year + def pv(fv, r, y, n) + fv / ((1 + (r / n))**(y * n)) + end + + # Calculates the interest given pv = present value, fv = future value, y = years, n = periods per year + def i(pv, fv, y, n) + n * ((fv / pv) ** (1 / (y.to_f * n)) - 1) + end + + # Calculates the number of years given the pv = present value, fv = future value, r = annual interest, n = periods per year + def y(pv, fv, r, n) + Math.log(fv / pv) / (n * Math.log(1 + (r / n))) + end + + def i_to_apr(r, n) + ((1 + (r / n)) ** n) - 1 + end + + def apr_to_i(apr, n) + n * ((1 + apr) ** (1/n.to_f) - 1) + end + + alias_method :present_value, :pv + alias_method :future_value, :fv + alias_method :interest, :i + alias_method :years, :y + alias_method :annual_interest_to_apr, :i_to_apr + alias_method :apr_to_annual_interest, :apr_to_i + end + end +end \ No newline at end of file
pearl-zz/jr_test
121ffd6ac6dde07a4b43e7099c019ac61df04a20
fix some bugs
diff --git a/app/models/account.rb b/app/models/account.rb index 1fa00e2..d5cb457 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -1,18 +1,18 @@ class Account < ActiveRecord::Base has_many :posts has_many :comments has_many :secret_models jr_model :fields => [:name, :login, :email] jr_include_association :posts, :when => :first_order - jr_include_association :comments, :when => :first_order + jr_include_association :comments, :when => :always jr_before_serialize :add_stuff_to_bundle def self.add_stuff_to_bundle(outgoing_bundle, incoming_bundle) outgoing_bundle[:custom_message] = "Hi Mom!" end end diff --git a/app/models/comment.rb b/app/models/comment.rb index 29019a9..0d94f23 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -1,10 +1,10 @@ class Comment < ActiveRecord::Base belongs_to :account belongs_to :post jr_model :fields => [:message] - jr_include_association :post, :when => :passive - jr_include_association :account, :when => :passive + jr_include_association :post, :when => :always + jr_include_association :account, :when => :always end diff --git a/app/models/post.rb b/app/models/post.rb index 0b1bc93..e41e2d1 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -1,10 +1,10 @@ class Post < ActiveRecord::Base belongs_to :account has_many :comments jr_model :fields => [:message] - jr_include_association :comments, :when => :second_order - jr_include_association :account, :when => :passive + jr_include_association :comments, :when => :always + jr_include_association :account, :when => :second_order end diff --git a/config/environments/development.rb b/config/environments/development.rb index dd38a16..e7b4ea4 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -1,26 +1,31 @@ JrTest::Application.configure do # Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin + + + + + end
pingviini/jyu.pas.wsse
c14f77d85bfc6d7ea87e1904b4426af5b1f8c4d7
Added missing files.
diff --git a/jyu/pas/wsse/README.txt b/jyu/pas/wsse/README.txt index 43f41e4..56e9636 100644 --- a/jyu/pas/wsse/README.txt +++ b/jyu/pas/wsse/README.txt @@ -1,51 +1,73 @@ Tests for jyu.pas.wsse test setup ---------- >>> from Testing.ZopeTestCase import user_password >>> from Products.Five.testbrowser import Browser >>> browser = Browser() Plugin setup ------------ >>> self.setRoles(('Manager',)) >>> from Products.PloneTestCase import PloneTestCase as ptc >>> browser.open('http://nohost/plone/login_form') >>> browser.getControl(name='__ac_name').value = ptc.default_user >>> browser.getControl(name='__ac_password').value = ptc.default_password >>> browser.getControl('Log in').click() >>> acl_users_url = "%s/acl_users" % self.portal.absolute_url() >>> browser.open("%s/manage_main" % acl_users_url) >>> browser.url 'http://nohost/plone/acl_users/manage_main' >>> form = browser.getForm(index=0) >>> select = form.getControl(name=':action') jyu.pas.wsse should be in the list of installable plugins: >>> 'WSSE Helper' in select.displayOptions True and we can select it: >>> select.getControl('WSSE Helper').click() >>> select.displayValue ['WSSE Helper'] >>> select.value ['manage_addProduct/jyu.pas.wsse/manage_add_wsse_form'] we add 'Wsse Helper' to acl_users: >>> from jyu.pas.wsse.plugin import WsseHelper >>> myhelper = WsseHelper('myplugin', 'Wsse Helper') >>> self.portal.acl_users['myplugin'] = myhelper -and so on. Continue your tests here - >>> interact(locals()) - >>> 'ALL OK' - 'ALL OK' +We have WSSE plugin added so now we start testing if it works. +First we change news folder to private and then log off our admin +user. + + >>> portal_url = self.portal.absolute_url() + >>> browser.open(portal_url + '/news') + >>> browser.getLink('Advanced...').click() + >>> browser.getControl(name='workflow_action').getControl(value='retract').selected = True + >>> browser.getControl('Save').click() + >>> browser.contents + '...status...private...' + + >>> browser.getLink('Log out').click() + >>> browser.open(portal_url + '/news/atombrowser') + >>> browser.contents + '...Log in...' + +TODO: Need to add test user +Now we add WSSE Headers + >>> browser.addHeader('Authorization', 'WSSE profile="UsernameToken"') + >>> browser.addHeader('X-WSSE', 'UsernameToken Username="wsseuser", PasswordDigest="quR/EWLAV4xLf9Zqyw4pDmfV9OY=", Nonce="d36e316282959a9ed4c89851497a717f", Created="2003-12-15T14:43:07Z") + + >>> interact(locals()) + + >>> 'ALL OK' + 'ALL OK' diff --git a/jyu/pas/wsse/__init__.py b/jyu/pas/wsse/__init__.py index 17369ee..e6330a5 100644 --- a/jyu/pas/wsse/__init__.py +++ b/jyu/pas/wsse/__init__.py @@ -1,8 +1,11 @@ +from zope.i18nmessageid import MessageFactory import install +_ = MessageFactory('jyu.pas.wsse') + install.register_wsse_plugin() def initialize(context): """Initializer called when used as a Zope 2 product.""" install.register_wsse_plugin_class(context) diff --git a/jyu/pas/wsse/browser/configure.zcml b/jyu/pas/wsse/browser/configure.zcml index c2574c7..58a732a 100644 --- a/jyu/pas/wsse/browser/configure.zcml +++ b/jyu/pas/wsse/browser/configure.zcml @@ -1,8 +1,14 @@ <configure xmlns="http://namespaces.zope.org/zope" xmlns:five="http://namespaces.zope.org/five" xmlns:browser="http://namespaces.zope.org/browser" i18n_domain="jyu.pas.wsse"> + <browser:page + for="..interface.IWsse" + name="wsse-controlpanel" + class=".controlpanel.WsseControlPanel" + permission="cmf.ManagePortal" + /> </configure> diff --git a/jyu/pas/wsse/interface.py b/jyu/pas/wsse/interface.py index 83a3485..cf6d894 100644 --- a/jyu/pas/wsse/interface.py +++ b/jyu/pas/wsse/interface.py @@ -1,4 +1,26 @@ from Products.PluggableAuthService import interfaces - +from zope.interface import Interface +from zope import schema +from zope.i18nmessageid import MessageFactory +_ = MessageFactory('jyu.pas.wsse') + class IWsseHelper(interfaces.plugins.IExtractionPlugin): """interface for WsseHelper.""" + + +class IWsseConfiguration(Interface): + """ Configuration for WSSE Pas Plugin """ + + apiKey = schema.ASCIILine( + title = _(u"API key"), + description = _(u"API key for WSSE Authorization"), + required = True, + ) + + +class IWsseControlPanel(Interface): + """ Control panel for Oembed Plone API """ + + +class IWsse(IWsseConfiguration): + """ WSSE marker """ diff --git a/jyu/pas/wsse/plugins/extraction.py b/jyu/pas/wsse/plugins/extraction.py index 0bd7367..796e7e9 100644 --- a/jyu/pas/wsse/plugins/extraction.py +++ b/jyu/pas/wsse/plugins/extraction.py @@ -1,24 +1,30 @@ from AccessControl.SecurityInfo import ClassSecurityInfo from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin class ExtractionPlugin(BasePlugin): """Extracts login name and credentials from a request. """ security = ClassSecurityInfo() security.declarePrivate('extractCredentials') def extractCredentials(self, request): """request -> {...} o Return a mapping of any derived credentials. o Return an empty mapping to indicate that the plugin found no appropriate credentials. """ creds = {} - #add your code here + if request.hasattr('X-WSSE'): + nonce = request.get('nonce') + created = request.get('Created') + else: + pass + + return creds diff --git a/jyu/pas/wsse/setuphandlers.py b/jyu/pas/wsse/setuphandlers.py index 93adee4..4d4e338 100644 --- a/jyu/pas/wsse/setuphandlers.py +++ b/jyu/pas/wsse/setuphandlers.py @@ -1,21 +1,21 @@ from Products.PlonePAS.Extensions.Install import activatePluginInterfaces from Products.CMFCore.utils import getToolByName from StringIO import StringIO from install import manage_add_wsse_helper def importVarius(context): - ''' Install the ExamplePAS plugin + ''' Install the WSSE plugin ''' out = StringIO() portal = context.getSite() uf = getToolByName(portal, 'acl_users') installed = uf.objectIds() if 'WSSE PAS Plugin' not in installed: - addExamplePlugin(uf, 'wsse', 'WSSE PAS Plugin') + manage_add_wsse_helper(uf, 'wsse', 'WSSE PAS Plugin') activatePluginInterfaces(portal, 'wsse', out) else: print >> out, 'wsse already installed' print out.getvalue() \ No newline at end of file
pingviini/jyu.pas.wsse
5a811535e65524c6c00faf472224bd2bf84ae0f5
Added control panel
diff --git a/jyu/pas/wsse/browser/control-panel.pt b/jyu/pas/wsse/browser/control-panel.pt new file mode 100644 index 0000000..9527af6 --- /dev/null +++ b/jyu/pas/wsse/browser/control-panel.pt @@ -0,0 +1,225 @@ +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:metal="http://xml.zope.org/namespaces/metal" + xmlns:tal="http://xml.zope.org/namespaces/tal" + xmlns:i18n="http://xml.zope.org/namespaces/i18n" + xml:lang="en" lang="en" + tal:omit-tag="" + metal:define-macro="controlpanel" + i18n:domain="plone"> + +<metal:block use-macro="context/prefs_main_template/macros/master"> + +<metal:block metal:fill-slot="top_slot" + tal:define="dummy python:request.set('disable_border', 1)" /> + +<body> + +<div metal:fill-slot="prefs_configlet_main"> + + <div metal:define-macro="form"> + + <div id="viewspace" metal:define-slot="viewspace"> + + <metal:block define-macro="header"> + + <dl tal:define="status view/status" + tal:condition="status" + class="portalMessage info"> + <dt i18n:translate=""> + Info + </dt> + <dd tal:content="view/status" /> + </dl> + + </metal:block> + + <h1 class="documentFirstHeading" + i18n:translate="" + tal:condition="view/label" + tal:content="view/label" + metal:define-slot="heading"> + Do something + </h1> + + <a href="" + class="link-parent" + tal:attributes="href string:$portal_url/plone_control_panel" + i18n:translate="label_up_to_plone_setup"> + Up to Site Setup + </a> + + <p i18n:translate="" + tal:condition="view/description" + tal:content="view/description"> + Description + </p> + + <form action="." + metal:define-macro="master" + tal:define="is_fieldsets view/is_fieldsets" + tal:attributes="action request/URL; + class python: is_fieldsets and 'edit-form enableFormTabbing enableUnloadProtection' or default" + method="post" + class="edit-form enableUnloadProtection" + enctype="multipart/form-data" + id="zc.page.browser_form"> + + <input type="hidden" + name="fieldset.current" + value="" + tal:attributes="value request/fieldset.current | string:" /> + + <div metal:define-slot="extra_info" tal:replace="nothing"> + </div> + + <fieldset tal:condition="not: is_fieldsets"> + <legend tal:define="form_name view/form_name|nothing" + tal:condition="form_name" + tal:content="form_name">Form name</legend> + <tal:block tal:repeat="widget view/widgets"> + + <div class="field" + tal:define="description widget/hint; + error widget/error" + tal:attributes="class python:'field'+(error and ' error' or '')"> + + <label i18n:translate="" + tal:attributes="for widget/name" + tal:content="widget/label"> + label + </label> + + <span class="fieldRequired" + title="Required" + i18n:attributes="title title_required;" + i18n:translate="label_required" + tal:condition="widget/required"> + (Required) + </span> + + <div class="formHelp" + i18n:translate="" + tal:content="description" + tal:condition="description"> + field description + </div> + + <div tal:condition="error" + tal:content="structure error"> + The Error + </div> + + <div class="widget" tal:content="structure widget"> + <input type="text" /> + + </div> +<script language="javascript" type="text/javascript"> +function randomString() { + var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; + var string_length = 25; + var randomstring = ''; + for (var i=0; i<string_length; i++) { + var rnum = Math.floor(Math.random() * chars.length); + randomstring += chars.substring(rnum,rnum+1); + } + field = document.getElementById('form.apiKey'); + field.value = randomstring; +} +</script> + +<input type="button" value="Create Random Key" onClick="randomString();">&nbsp; + </div> + + </tal:block> + + </fieldset> + + <fieldset tal:attributes="id python:'fieldset-%s' % fieldset.id" + tal:condition="is_fieldsets" + tal:repeat="fieldset view/form_fields/fieldsets"> + <legend tal:define="form_name fieldset/label" + tal:condition="form_name" + tal:attributes="id python:'fieldsetlegend-%s' % fieldset.id" + tal:content="form_name">Form name</legend> + + <p i18n:translate="" + tal:condition="fieldset/description" + tal:content="fieldset/description"> + Description + </p> + + <tal:block tal:repeat="widget fieldset/widgets"> + + <div class="field" + tal:define="description widget/hint; + error widget/error" + tal:attributes="class python:'field'+(error and ' error' or '')"> + + <label i18n:translate="" + tal:define="name widget/name" + tal:attributes="for widget/associateLabelWithInputControl|name" + tal:content="widget/label"> + label + </label> + + <span class="fieldRequired" + title="Required" + i18n:attributes="title title_required;" + i18n:translate="label_required" + tal:condition="widget/required"> + (Required) + </span> + + <div class="formHelp" + i18n:translate="" + tal:content="description" + tal:condition="description"> + field description + </div> + + <div tal:condition="error" + tal:content="structure error"> + The Error + </div> + + <div class="widget" tal:content="structure widget"> + <input type="text" /> + + </div> + </div> + + </tal:block> + + </fieldset> + + <metal:block define-slot="above_buttons" /> + + <div class="visualClear"><!-- --></div> + + <div id="actionsView" class="formControls"> + <span class="actionButtons" + tal:condition="view/availableActions" + metal:define-slot="bottom_buttons"> + <input tal:repeat="action view/actions" + tal:replace="structure action/render" /> + </span> + </div> + + <input tal:replace="structure context/@@authenticator/authenticator" /> + + </form> + </div> + + <script type="text/javascript" + tal:define="extra_script view/extra_script | nothing" + tal:condition="extra_script" + tal:content="structure extra_script"> + </script> + + </div> + +</div> +</body> + +</metal:block> +</html> diff --git a/jyu/pas/wsse/browser/controlpanel.py b/jyu/pas/wsse/browser/controlpanel.py new file mode 100644 index 0000000..5e51df4 --- /dev/null +++ b/jyu/pas/wsse/browser/controlpanel.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- + +from zope.component import getUtility +from zope.interface import implements + +from plone.fieldsets.fieldsets import FormFields +from plone.app.controlpanel.form import ControlPanelForm +from jyu.pas.wsse import _ +from jyu.pas.wsse.interface import IWsseControlPanel +from jyu.pas.wsse.interface import IWsseConfiguration +from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile + +class WsseControlPanel(ControlPanelForm): + """ Pathkey control panel """ + implements(IWsseControlPanel) + template = ViewPageTemplateFile('control-panel.pt') + form_fields = FormFields(IWsseConfiguration) + + form_name = _(u"WSSE API Key") + label = _(u"WSSE API Key") + description = _(u"Set or modify the WSSE API Key") \ No newline at end of file diff --git a/jyu/pas/wsse/profiles/default/componentregistry.xml b/jyu/pas/wsse/profiles/default/componentregistry.xml new file mode 100644 index 0000000..18a1b34 --- /dev/null +++ b/jyu/pas/wsse/profiles/default/componentregistry.xml @@ -0,0 +1,9 @@ +<?xml version="1.0"?> +<componentregistry> + <adapters/> + <utilities> + <utility + interface="jyu.pas.wsse.interface.IWsse" + object="portal_wsse"/> + </utilities> +</componentregistry> \ No newline at end of file diff --git a/jyu/pas/wsse/profiles/default/controlpanel.xml b/jyu/pas/wsse/profiles/default/controlpanel.xml new file mode 100644 index 0000000..dc77929 --- /dev/null +++ b/jyu/pas/wsse/profiles/default/controlpanel.xml @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<object name="portal_controlpanel" meta_type="Plone Control Panel Tool"> + <configlet title="WSSE" + action_id="wsse" appId="WsseAPI" + category="Products" + condition_expr="" + url_expr="string:${portal_url}/portal_wsse/@@wsse-controlpanel" + visible="True"> + <permission>Manage portal</permission> + </configlet> +</object> \ No newline at end of file diff --git a/jyu/pas/wsse/profiles/default/toolset.xml b/jyu/pas/wsse/profiles/default/toolset.xml new file mode 100644 index 0000000..1f2d523 --- /dev/null +++ b/jyu/pas/wsse/profiles/default/toolset.xml @@ -0,0 +1,5 @@ +<?xml version="1.0"?> +<tool-setup> + <required tool_id="portal_wsse" + class="jyu.pas.wsse.utils.Wsse"/> +</tool-setup> \ No newline at end of file diff --git a/jyu/pas/wsse/utils.py b/jyu/pas/wsse/utils.py new file mode 100644 index 0000000..085b6fa --- /dev/null +++ b/jyu/pas/wsse/utils.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- + +from zope.interface import implements +from zope.schema.fieldproperty import FieldProperty +from zope.component import getUtility +from zope.interface import classProvides + +from jyu.pas.wsse.interface import IWsse +from jyu.pas.wsse.interface import IWsseConfiguration + +from OFS.SimpleItem import SimpleItem + + +def form_adapter(context): + """Form Adapter""" + return getUtility(IWsse) + + +class Wsse(SimpleItem): + """Wsse Utility""" + implements(IWsse) + + classProvides( + IWsseConfiguration, + ) + + apiKey = FieldProperty(IWsseConfiguration['apiKey'])
robinvanderknaap/MvcSiteMap
06323ef01a1f51b5f0647b8a84d1af5303c9b026
Added license and readme file
diff --git a/License.txt b/License.txt new file mode 100644 index 0000000..dfcbc2b --- /dev/null +++ b/License.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..5eb6a3f --- /dev/null +++ b/README.txt @@ -0,0 +1 @@ +Sample application for ASP.NET MVC xml sitemap provider \ No newline at end of file
dim/retrospectiva.scm_ticketing
0a5d51ffc6fdc77815fe947cf03c68891a06813b
Added more specs
diff --git a/spec/fixtures/statuses.yml b/spec/fixtures/statuses.yml index 6aac7d0..3012216 100644 --- a/spec/fixtures/statuses.yml +++ b/spec/fixtures/statuses.yml @@ -1,21 +1,26 @@ open: name: Open rank: 1 state_id: 1 statement_id: 2 default_value: true assigned: name: Assigned rank: 2 statement_id: 1 state_id: 2 +under_development: + name: Under Development + rank: 3 + state_id: 2 + statement_id: 1 invalid: name: Invalid - rank: 3 + rank: 4 statement_id: 3 state_id: 3 fixed: name: Fixed - rank: 4 + rank: 5 statement_id: 1 state_id: 3 diff --git a/spec/models/changeset_spec.rb b/spec/models/changeset_spec.rb index 9675561..1aae10a 100644 --- a/spec/models/changeset_spec.rb +++ b/spec/models/changeset_spec.rb @@ -1,55 +1,59 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Changeset do fixtures :all - def new_changeset(options = {}) + def changeset(options = {}) options.reverse_merge!(:revision => 'ABCDEFGH', :author => 'agent', :log => "[##{tickets(:open).id}] Fixed Problem (s:fixed u:agent)") - repositories(:git).changesets.create(options) + @changeset ||= repositories(:git).changesets.create(options) end it 'should create a valid changeset' do - changeset = new_changeset changeset.should_not be_new_record changeset.projects.should have(1).record end it 'should retain the original log message' do message = "[##{tickets(:open).id}](status:Fixed user:agent) Added support for on the fly switching between output sample frequencies & the extra desired frequencies (48kHz, 32kHz, 24kHz, 12kHz, 8kHz)." - changeset = new_changeset(:log => message) - changeset.should_not be_new_record + changeset(:log => message).should_not be_new_record changeset.log.should == message end - + describe 'after a new changeset was created' do it 'should update the tickets' do - ticket = tickets(:open) - ticket.status.should == statuses(:open) - new_changeset - ticket.reload.status.should == statuses(:fixed) - ticket.assigned_user.should == users(:agent) + tickets(:open).status.should == statuses(:open) + changeset.should_not be_new_record + tickets(:open).reload.status.should == statuses(:fixed) + tickets(:open).assigned_user.should == users(:agent) + end + + it 'should update tickets (with complex property names)' do + message = %([##{tickets(:open).id}](status:"Under Development") Fixed a little bug) + changeset(:log => message).should_not be_new_record + tickets(:open).reload.status.should == statuses(:under_development) end it 'should NOT update tickets if author cannot be found' do - new_changeset(:author => 'noone') + changeset(:author => 'noone').should_not be_new_record tickets(:open).status.should == statuses(:open) - tickets(:open).assigned_user.should be_nil + tickets(:open).assigned_user.should be_nil end it 'should NOT update tickets if tickets cannot be found' do - new_changeset(:log => '[#99] Fixed Problem (s:fixed u:agent)') + changeset(:log => '[#99] Fixed Problem (s:fixed u:agent)').should_not be_new_record tickets(:open).status.should == statuses(:open) tickets(:open).assigned_user.should be_nil end it 'should NOT update tickets if user has no permission to do so' do groups(:Default).update_attribute(:permissions, {}) + changeset.should_not be_new_record tickets(:open).status.should == statuses(:open) tickets(:open).assigned_user.should be_nil end end end \ No newline at end of file diff --git a/spec/models/commit_log_parser_spec.rb b/spec/models/commit_log_parser_spec.rb index a01277d..dfc5c0b 100644 --- a/spec/models/commit_log_parser_spec.rb +++ b/spec/models/commit_log_parser_spec.rb @@ -1,61 +1,70 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Repository::CommitLogParser do def parse(line) result = [] Repository::CommitLogParser.new('REVABC', line).each do |parsed| result << parsed end result end it 'should ignore lines without a ticket reference' do parse("(status:fixed assigned:mabs) fixed a little bug").should == [] end it 'should ignore lines without property changes' do parse("[#1234] fixed a little bug").should == [] end it 'should correctly parse pre-commit lines' do parse("[#1234](status:fixed assigned:mabs) fixed a little bug").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse split-commit lines' do parse("[#1234] fixed a little bug (status:fixed assigned:mabs)").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse post-commit lines' do parse("fixed a little bug [#1234] (status:fixed assigned:mabs)").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse lines with lots of whitespaces' do parse(" [#1234] fixed a little bug (status:fixed assigned:mabs) ").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse unusual property patterns' do parse("[#1234] fixed a little bug (status : \"fixed\" , assigned : mabs)").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] parse("fixed a little bug [#1234] (status : \"fixed\" assigned :mabs)").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end + + it 'should correctly parse quoted property values' do + parse(%Q([#11](status:"Under Development") Fixed a little bug)).should == [ + { :id => 11, :content => '[REVABC] Fixed a little bug', :properties => { 'status' => 'Under Development' } } + ] + end + + + it 'should correctly parse multiple curly-bracket-blocks' do message = "[#16](status:Fixed user:schmidtw) Added support for on the fly switching between output sample frequencies & the extra desired frequencies (48kHz, 32kHz, 24kHz, 12kHz, 8kHz)." parse(message).should == [ { :id => 16, :content => '[REVABC] Added support for on the fly switching between output sample frequencies & the extra desired frequencies (48kHz, 32kHz, 24kHz, 12kHz, 8kHz).', :properties => { 'status' => 'Fixed', 'user' => 'schmidtw' } } ] end end \ No newline at end of file
dim/retrospectiva.scm_ticketing
0735a17dcd822de2bf296e7c2042b20c89b255e6
Improved parser
diff --git a/lib/repository/commit_log_parser.rb b/lib/repository/commit_log_parser.rb index a85e1cc..afb6fdb 100755 --- a/lib/repository/commit_log_parser.rb +++ b/lib/repository/commit_log_parser.rb @@ -1,56 +1,56 @@ #-- # Copyright (c) 2009 # Please read LICENSE document for more information. #++ class Repository::CommitLogParser TICKET_REF = /\[\#(\d+)\]/ PROPERTY_KEY = /\w+/ QUOTED_VALUE = /['"][^'"]+['"]/ UNQUOTED_VALUE = /\w+/ SEPARATOR = / *: */ PROPERTY_ITEM = /(#{PROPERTY_KEY})#{SEPARATOR}(#{QUOTED_VALUE}|#{UNQUOTED_VALUE})/ PROPERTY_BLOCK = /\(#{PROPERTY_ITEM}(?:[ ,]+#{PROPERTY_ITEM})*\)/ attr_reader :commit_id, :log def initialize(commit_id, log) @commit_id = commit_id @log = log.to_s end # Yields a hash for each line which has a ticket reference def each(&block) log.each_line do |line| parsed = parse_line(line) yield parsed if parsed end end # Returns a hash of the id, properties and content (comment) def parse_line(line) line = line.gsub(TICKET_REF, '') - - ticket_id = $1.to_i + + ticket_id = $1.to_i return nil if ticket_id.zero? properties = format_properties(line.scan(PROPERTY_BLOCK)) return nil if properties.blank? { :id => ticket_id, :content => content(line.gsub(PROPERTY_BLOCK, '').squish), :properties => properties } end protected def format_properties(properties) - properties = properties.flatten.map do |value| + properties = properties.flatten.compact.map do |value| value.gsub(/^['"]/, '').gsub(/['"]$/, '') end Hash[*properties] end def content(content) "[#{commit_id}] #{content.lstrip}".strip end end diff --git a/spec/models/commit_log_parser_spec.rb b/spec/models/commit_log_parser_spec.rb index 5cb8caa..a01277d 100644 --- a/spec/models/commit_log_parser_spec.rb +++ b/spec/models/commit_log_parser_spec.rb @@ -1,61 +1,61 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Repository::CommitLogParser do def parse(line) result = [] Repository::CommitLogParser.new('REVABC', line).each do |parsed| result << parsed end result end it 'should ignore lines without a ticket reference' do parse("(status:fixed assigned:mabs) fixed a little bug").should == [] end it 'should ignore lines without property changes' do parse("[#1234] fixed a little bug").should == [] end it 'should correctly parse pre-commit lines' do parse("[#1234](status:fixed assigned:mabs) fixed a little bug").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse split-commit lines' do parse("[#1234] fixed a little bug (status:fixed assigned:mabs)").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse post-commit lines' do parse("fixed a little bug [#1234] (status:fixed assigned:mabs)").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse lines with lots of whitespaces' do parse(" [#1234] fixed a little bug (status:fixed assigned:mabs) ").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse unusual property patterns' do parse("[#1234] fixed a little bug (status : \"fixed\" , assigned : mabs)").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] parse("fixed a little bug [#1234] (status : \"fixed\" assigned :mabs)").should == [ { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } - ] + ] end it 'should correctly parse multiple curly-bracket-blocks' do message = "[#16](status:Fixed user:schmidtw) Added support for on the fly switching between output sample frequencies & the extra desired frequencies (48kHz, 32kHz, 24kHz, 12kHz, 8kHz)." parse(message).should == [ { :id => 16, :content => '[REVABC] Added support for on the fly switching between output sample frequencies & the extra desired frequencies (48kHz, 32kHz, 24kHz, 12kHz, 8kHz).', :properties => { 'status' => 'Fixed', 'user' => 'schmidtw' } } ] end end \ No newline at end of file diff --git a/spec/models/repository/abstract_spec.rb b/spec/models/repository/abstract_spec.rb index f2f4431..30e2fe2 100644 --- a/spec/models/repository/abstract_spec.rb +++ b/spec/models/repository/abstract_spec.rb @@ -1,25 +1,25 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Repository::Abstract do fixtures :all before do @repository = repositories(:git) end describe 'bulk synchronization' do it 'should update the tickets after the synchronisation' do @changeset = mock_model(Changeset) @repository.should_receive(:synchronize_without_log_parsing!).and_return([@changeset]) @changeset.should_receive(:parse_log_and_update_tickets!) @repository.sync_changesets end it 'should perform correctly' do @repository.sync_changesets - @repository.changesets.should have(10).records + @repository.changesets.should have(11).records end end end \ No newline at end of file
dim/retrospectiva.scm_ticketing
a02561e19ed31f84e0748729a37a97e848bad8ce
Added more specs
diff --git a/spec/models/changeset_spec.rb b/spec/models/changeset_spec.rb index a32fcd8..9675561 100644 --- a/spec/models/changeset_spec.rb +++ b/spec/models/changeset_spec.rb @@ -1,48 +1,55 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Changeset do fixtures :all def new_changeset(options = {}) options.reverse_merge!(:revision => 'ABCDEFGH', :author => 'agent', :log => "[##{tickets(:open).id}] Fixed Problem (s:fixed u:agent)") repositories(:git).changesets.create(options) end it 'should create a valid changeset' do changeset = new_changeset changeset.should_not be_new_record changeset.projects.should have(1).record end + + it 'should retain the original log message' do + message = "[##{tickets(:open).id}](status:Fixed user:agent) Added support for on the fly switching between output sample frequencies & the extra desired frequencies (48kHz, 32kHz, 24kHz, 12kHz, 8kHz)." + changeset = new_changeset(:log => message) + changeset.should_not be_new_record + changeset.log.should == message + end describe 'after a new changeset was created' do it 'should update the tickets' do ticket = tickets(:open) ticket.status.should == statuses(:open) new_changeset ticket.reload.status.should == statuses(:fixed) ticket.assigned_user.should == users(:agent) end it 'should NOT update tickets if author cannot be found' do new_changeset(:author => 'noone') tickets(:open).status.should == statuses(:open) tickets(:open).assigned_user.should be_nil end it 'should NOT update tickets if tickets cannot be found' do new_changeset(:log => '[#99] Fixed Problem (s:fixed u:agent)') tickets(:open).status.should == statuses(:open) tickets(:open).assigned_user.should be_nil end it 'should NOT update tickets if user has no permission to do so' do groups(:Default).update_attribute(:permissions, {}) tickets(:open).status.should == statuses(:open) tickets(:open).assigned_user.should be_nil end end end \ No newline at end of file diff --git a/spec/models/commit_log_parser_spec.rb b/spec/models/commit_log_parser_spec.rb index 7cde936..5cb8caa 100644 --- a/spec/models/commit_log_parser_spec.rb +++ b/spec/models/commit_log_parser_spec.rb @@ -1,54 +1,61 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Repository::CommitLogParser do def parse(line) result = [] Repository::CommitLogParser.new('REVABC', line).each do |parsed| result << parsed end result end it 'should ignore lines without a ticket reference' do parse("(status:fixed assigned:mabs) fixed a little bug").should == [] end it 'should ignore lines without property changes' do parse("[#1234] fixed a little bug").should == [] end it 'should correctly parse pre-commit lines' do parse("[#1234](status:fixed assigned:mabs) fixed a little bug").should == [ - :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse split-commit lines' do parse("[#1234] fixed a little bug (status:fixed assigned:mabs)").should == [ - :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse post-commit lines' do parse("fixed a little bug [#1234] (status:fixed assigned:mabs)").should == [ - :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse lines with lots of whitespaces' do parse(" [#1234] fixed a little bug (status:fixed assigned:mabs) ").should == [ - :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end it 'should correctly parse unusual property patterns' do parse("[#1234] fixed a little bug (status : \"fixed\" , assigned : mabs)").should == [ - :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] parse("fixed a little bug [#1234] (status : \"fixed\" assigned :mabs)").should == [ - :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + { :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } } ] end + it 'should correctly parse multiple curly-bracket-blocks' do + message = "[#16](status:Fixed user:schmidtw) Added support for on the fly switching between output sample frequencies & the extra desired frequencies (48kHz, 32kHz, 24kHz, 12kHz, 8kHz)." + parse(message).should == [ + { :id => 16, :content => '[REVABC] Added support for on the fly switching between output sample frequencies & the extra desired frequencies (48kHz, 32kHz, 24kHz, 12kHz, 8kHz).', :properties => { 'status' => 'Fixed', 'user' => 'schmidtw' } } + ] + end + end \ No newline at end of file diff --git a/spec/models/ticket_change_spec.rb b/spec/models/ticket_change_spec.rb index 2e0664f..6278bb9 100644 --- a/spec/models/ticket_change_spec.rb +++ b/spec/models/ticket_change_spec.rb @@ -1,127 +1,136 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe TicketChange do fixtures :all before do @ticket = tickets(:open) @change = @ticket.changes.new end describe 'updating content' do it 'should update' do @change.set_attributes_from_scm_reference(:properties => {}, :content => 'Fixed Bug') @change.content.should == 'Fixed Bug' end it 'should not update if not present' do @change.set_attributes_from_scm_reference(:properties => {}, :content => '') @change.content.should be_nil end end describe 'updating assigned user' do it 'should update by username' do @change.set_attributes_from_scm_reference(:properties => { 'user' => 'agent' }) @change.assigned_user.should == users(:agent) end it 'should update by email' do @change.set_attributes_from_scm_reference(:properties => { 'user' => '[email protected]' }) @change.assigned_user.should == users(:agent) end it 'should update by alternative key' do @change.set_attributes_from_scm_reference(:properties => { 'assigned' => 'agent' }) @change.assigned_user.should == users(:agent) end it 'should update by short key' do @change.set_attributes_from_scm_reference(:properties => { 'u' => 'agent' }) @change.assigned_user.should == users(:agent) end it 'should not update if user cannot be found' do @change.set_attributes_from_scm_reference(:properties => { 'user' => 'me' }) @change.assigned_user.should be_nil end end describe 'updating milestone' do it 'should update by name' do @change.set_attributes_from_scm_reference(:properties => { 'milestone' => 'next release' }) @change.milestone.should == milestones(:next_release) end it 'should update by name (case insensitive)' do @change.set_attributes_from_scm_reference(:properties => { 'milestone' => 'Next Release' }) @change.milestone.should == milestones(:next_release) end it 'should update via shortcut' do @change.set_attributes_from_scm_reference(:properties => { 'm' => 'Next Release' }) @change.milestone.should == milestones(:next_release) end it 'should not update if milestone cannot be found' do @change.set_attributes_from_scm_reference(:properties => { 'milestone' => 'invalid' }) @change.milestone.should be_nil end end describe 'updating status' do it 'should update by name' do @change.set_attributes_from_scm_reference(:properties => { 'status' => 'fixed' }) @change.status.should == statuses(:fixed) end it 'should update by name (case insensitive)' do @change.set_attributes_from_scm_reference(:properties => { 'status' => 'FIXED' }) @change.status.should == statuses(:fixed) end it 'should update via shortcut' do @change.set_attributes_from_scm_reference(:properties => { 's' => 'fixed' }) @change.status.should == statuses(:fixed) end it 'should not update if status cannot be found' do @change.set_attributes_from_scm_reference(:properties => { 'status' => 'accomplished' }) @change.status.should == statuses(:open) end end - describe 'updating priority' do + describe 'updating priority' do it 'should update by name' do @change.set_attributes_from_scm_reference(:properties => { 'priority' => 'major' }) @change.priority.should == priorities(:major) end it 'should update by name (case insensitive)' do @change.set_attributes_from_scm_reference(:properties => { 'priority' => 'MAJOR' }) @change.priority.should == priorities(:major) end it 'should update via shortcut' do @change.set_attributes_from_scm_reference(:properties => { 'p' => 'major' }) @change.priority.should == priorities(:major) end it 'should not update if priority cannot be found' do @change.set_attributes_from_scm_reference(:properties => { 'priority' => 'invalid' }) @change.priority.should == priorities(:normal) end end + describe 'multiple updates' do + + it 'should update all attributes' do + @change.set_attributes_from_scm_reference( :properties => { 'status' => 'Fixed', 'user' => 'agent' } ) + @change.status.should == statuses(:fixed) + @change.assigned_user.should == users(:agent) + end + + end end \ No newline at end of file
dim/retrospectiva.scm_ticketing
74e331ef486476809193c9731806fe3a226fcdc0
Fixed bulk update issue / Updated specs
diff --git a/ext/changeset.rb b/ext/changeset.rb index bb54e18..bd8acff 100644 --- a/ext/changeset.rb +++ b/ext/changeset.rb @@ -1,40 +1,40 @@ #-- # Copyright (c) 2009 Mathew Abonyi, Dimitrij Denissenko # Please read LICENSE document for more information. #++ # This extension to the Changeset model translates SCM ticket # updates into actual changes on each referenced ticket. Changeset.class_eval do after_create :parse_log_and_update_tickets! protected def parse_log_and_update_tickets! return true if bulk_synchronization || user.blank? Repository::CommitLogParser.new(revision, log).each do |reference| logger.info "\n\n[SCM Ticket Update] ------------------------------" logger.info "Detected reference: #{reference.inspect}" ticket = Ticket.find :first, :conditions => ['id = ? AND project_id IN (?)', reference[:id], projects.active.map(&:id)] - + if ticket && user.permitted?(:tickets, :update, :project => ticket.project) logger.debug "Updating ticket: #{ticket.id}" ticket_change = ticket.changes.new do |record| record.user = user record.set_attributes_from_scm_reference(reference) end - + if ticket_change.save logger.info "Successfully updated ticket: #{ticket.id}" else logger.info "Failed to update ticket: #{ticket.id}. #{ticket_change.errors.full_messages.inspect}" end end end end end diff --git a/ext/repository/abstract.rb b/ext/repository/abstract.rb index 725c7c3..5f5a30c 100644 --- a/ext/repository/abstract.rb +++ b/ext/repository/abstract.rb @@ -1,12 +1,12 @@ Repository::Abstract.class_eval do protected def synchronize_with_log_parsing!(revisions) bulk_mode = revisions.size > 5 returning(synchronize_without_log_parsing!(revisions)) do |changesets| - changesets.each(&:parse_log_and_update_tickets!) if bulk_mode + changesets.each {|c| c.send :parse_log_and_update_tickets! } if bulk_mode end end alias_method_chain :synchronize!, :log_parsing end \ No newline at end of file diff --git a/spec/fixtures/groups.yml b/spec/fixtures/groups.yml index 9f52cd9..f5a6060 100644 --- a/spec/fixtures/groups.yml +++ b/spec/fixtures/groups.yml @@ -1,10 +1,10 @@ Default: - id: 1 name: Default permissions: | --- tickets: - create - update - view - watch + projects: retro \ No newline at end of file diff --git a/spec/fixtures/groups_projects.yml b/spec/fixtures/groups_projects.yml deleted file mode 100644 index 506e72b..0000000 --- a/spec/fixtures/groups_projects.yml +++ /dev/null @@ -1,3 +0,0 @@ -retrospectiva_default: - project_id: 1 - group_id: 1 diff --git a/spec/fixtures/groups_users.yml b/spec/fixtures/groups_users.yml deleted file mode 100644 index 1aec8eb..0000000 --- a/spec/fixtures/groups_users.yml +++ /dev/null @@ -1,6 +0,0 @@ -default_public: - user_id: 1 - group_id: 1 -default_agent: - user_id: 3 - group_id: 1 diff --git a/spec/fixtures/milestones.yml b/spec/fixtures/milestones.yml index a45a993..1ce1376 100644 --- a/spec/fixtures/milestones.yml +++ b/spec/fixtures/milestones.yml @@ -1,9 +1,8 @@ --- next_release: - id: 1 name: Next release - project_id: 1 + project: retro info: Long info due: <%= 3.months.since.to_s(:db) %> created_at: <%= 1.month.ago.to_s(:db) %> updated_at: <%= 1.month.ago.to_s(:db) %> diff --git a/spec/fixtures/priorities.yml b/spec/fixtures/priorities.yml index 19cf809..b766b08 100644 --- a/spec/fixtures/priorities.yml +++ b/spec/fixtures/priorities.yml @@ -1,14 +1,11 @@ --- normal: name: Normal - id: 1 rank: 2 default_value: true minor: name: Minor - id: 2 rank: 1 major: name: Major - id: 3 rank: 3 diff --git a/spec/fixtures/projects.yml b/spec/fixtures/projects.yml index a7843f5..6a73c53 100644 --- a/spec/fixtures/projects.yml +++ b/spec/fixtures/projects.yml @@ -1,8 +1,7 @@ --- retro: - id: 1 name: Retrospectiva info: Retrospectiva project closed: false short_name: retrospectiva - repository_id: 1 + repository: git diff --git a/spec/fixtures/repositories.yml b/spec/fixtures/repositories.yml index 15073bb..5226bd7 100644 --- a/spec/fixtures/repositories.yml +++ b/spec/fixtures/repositories.yml @@ -1,5 +1,4 @@ -svn: - name: SVN repository - id: 1 - path: ../../tmp/svn_test - type: Repository::Subversion +git: + name: GIT repository + path: ../../tmp/git_test.git + type: Repository::Git diff --git a/spec/fixtures/statuses.yml b/spec/fixtures/statuses.yml index 8ce8120..6aac7d0 100644 --- a/spec/fixtures/statuses.yml +++ b/spec/fixtures/statuses.yml @@ -1,25 +1,21 @@ open: - id: 1 name: Open rank: 1 state_id: 1 statement_id: 2 default_value: true assigned: - id: 2 name: Assigned rank: 2 statement_id: 1 state_id: 2 invalid: - id: 3 name: Invalid rank: 3 statement_id: 3 state_id: 3 fixed: - id: 4 name: Fixed rank: 4 statement_id: 1 state_id: 3 diff --git a/spec/fixtures/tickets.yml b/spec/fixtures/tickets.yml index 81e88fd..245ab88 100644 --- a/spec/fixtures/tickets.yml +++ b/spec/fixtures/tickets.yml @@ -1,13 +1,11 @@ --- open: - id: 1 - project_id: 1 + project: retro author: John Doe - priority_id: 1 + priority: normal summary: An open ticket content: Description - status_id: 1 + status: open email: [email protected] - milestone_id: created_at: <%= 4.months.ago.midnight.to_formatted_s(:db) %> updated_at: <%= 4.months.ago.midnight.to_formatted_s(:db) %> diff --git a/spec/fixtures/users.yml b/spec/fixtures/users.yml index 9fca6de..e44f25d 100644 --- a/spec/fixtures/users.yml +++ b/spec/fixtures/users.yml @@ -1,20 +1,20 @@ --- Public: - id: 1 name: admin: false username: Public password: fc0b88b7c9e2c896bcee4881d00d7bf5a7d2442d email: time_zone: London + groups: Default agent: # plain_password = password name: Agent admin: false - id: 3 password: b742714644f63a57f3bfe7dbe782451f0fe982b4 salt: 987654 username: agent email: [email protected] scm_name: agent time_zone: London private_key: 6b2c92007c38ca274ea45d8dd52f401b81ae44e6 + groups: Default diff --git a/spec/models/changeset_spec.rb b/spec/models/changeset_spec.rb index c8734dc..a32fcd8 100644 --- a/spec/models/changeset_spec.rb +++ b/spec/models/changeset_spec.rb @@ -1,46 +1,48 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Changeset do fixtures :all def new_changeset(options = {}) - options.reverse_merge!(:revision => 'ABCDEFGH', :author => 'agent', :log => '[#1] Fixed Problem (s:fixed u:agent)') - repositories(:svn).changesets.create(options) + options.reverse_merge!(:revision => 'ABCDEFGH', :author => 'agent', :log => "[##{tickets(:open).id}] Fixed Problem (s:fixed u:agent)") + repositories(:git).changesets.create(options) end it 'should create a valid changeset' do changeset = new_changeset changeset.should_not be_new_record changeset.projects.should have(1).record end describe 'after a new changeset was created' do it 'should update the tickets' do + ticket = tickets(:open) + ticket.status.should == statuses(:open) new_changeset - tickets(:open).status.should == statuses(:fixed) - tickets(:open).assigned_user.should == users(:agent) + ticket.reload.status.should == statuses(:fixed) + ticket.assigned_user.should == users(:agent) end it 'should NOT update tickets if author cannot be found' do new_changeset(:author => 'noone') tickets(:open).status.should == statuses(:open) tickets(:open).assigned_user.should be_nil end it 'should NOT update tickets if tickets cannot be found' do new_changeset(:log => '[#99] Fixed Problem (s:fixed u:agent)') tickets(:open).status.should == statuses(:open) tickets(:open).assigned_user.should be_nil end it 'should NOT update tickets if user has no permission to do so' do groups(:Default).update_attribute(:permissions, {}) tickets(:open).status.should == statuses(:open) tickets(:open).assigned_user.should be_nil end end end \ No newline at end of file diff --git a/spec/models/repository/abstract_spec.rb b/spec/models/repository/abstract_spec.rb index 38e3b81..f2f4431 100644 --- a/spec/models/repository/abstract_spec.rb +++ b/spec/models/repository/abstract_spec.rb @@ -1,25 +1,25 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Repository::Abstract do fixtures :all before do - @repository = repositories(:svn) + @repository = repositories(:git) end describe 'bulk synchronization' do it 'should update the tickets after the synchronisation' do @changeset = mock_model(Changeset) @repository.should_receive(:synchronize_without_log_parsing!).and_return([@changeset]) @changeset.should_receive(:parse_log_and_update_tickets!) @repository.sync_changesets end it 'should perform correctly' do @repository.sync_changesets @repository.changesets.should have(10).records end end end \ No newline at end of file
dim/retrospectiva.scm_ticketing
de4671087861a7accc31571555421cd9e11ace22
Initial Release
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..18f1b87 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ + ---------------------------------------------------------------------------- + Copyright (c) 2009 Mathew Abonyi, Dimitrij Denissenko + + 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: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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. + ---------------------------------------------------------------------------- + diff --git a/README b/README new file mode 100644 index 0000000..32db11b --- /dev/null +++ b/README @@ -0,0 +1,33 @@ + This extension allows Retrospectiva users to update tickets via + SCM log messages. + + Usage + ===== + + When you commit changes to your repository, you can automatically + update Retrospectiva tickets by using a special syntax in your commit + log message. + + The 'user', 'status', 'priority' and 'milestone' attributes can be set. + Multiple formats are supported. Examples: + + [#1234](status:fixed user:mabs) Fixed a little Bug + + [#1234] Fixed a little Bug (status:fixed priority:high) + + Fixed a little Bug [#1234](status:assigned milestone:upcoming) + + Attribute value with spaces must be put it in double quotes: + + [#1234](status:fixed milestone:"0.9.x (pre-alpha)") Fixed Bug + + Multiple tickets can be updated at the same time. + + [#1234](status:fixed user:dim priority:low) Fixed one problem + [#5678](status:fixed user:dim) Fixed another problem + + Details + ======= + + Written by Mathew Abonyi (http://www.mathewabonyi.com/) + Updated by Dimitrij Denissenko diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..8ed12c4 --- /dev/null +++ b/Rakefile @@ -0,0 +1,13 @@ +require(File.join(File.dirname(__FILE__), '..', '..', 'config', 'boot')) + +require 'rake' +require 'spec/rake/spectask' + +desc 'Default: run unit tests.' +task :default => :spec + +desc "Run the extension specs" +Spec::Rake::SpecTask.new(:spec) do |t| + t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] + t.spec_files = FileList["spec/**/*_spec.rb"] +end diff --git a/ext/changeset.rb b/ext/changeset.rb new file mode 100644 index 0000000..bb54e18 --- /dev/null +++ b/ext/changeset.rb @@ -0,0 +1,40 @@ +#-- +# Copyright (c) 2009 Mathew Abonyi, Dimitrij Denissenko +# Please read LICENSE document for more information. +#++ + +# This extension to the Changeset model translates SCM ticket +# updates into actual changes on each referenced ticket. +Changeset.class_eval do + after_create :parse_log_and_update_tickets! + + protected + + def parse_log_and_update_tickets! + return true if bulk_synchronization || user.blank? + + Repository::CommitLogParser.new(revision, log).each do |reference| + logger.info "\n\n[SCM Ticket Update] ------------------------------" + logger.info "Detected reference: #{reference.inspect}" + + ticket = Ticket.find :first, + :conditions => ['id = ? AND project_id IN (?)', reference[:id], projects.active.map(&:id)] + + if ticket && user.permitted?(:tickets, :update, :project => ticket.project) + logger.debug "Updating ticket: #{ticket.id}" + + ticket_change = ticket.changes.new do |record| + record.user = user + record.set_attributes_from_scm_reference(reference) + end + + if ticket_change.save + logger.info "Successfully updated ticket: #{ticket.id}" + else + logger.info "Failed to update ticket: #{ticket.id}. #{ticket_change.errors.full_messages.inspect}" + end + end + end + end + +end diff --git a/ext/repository/abstract.rb b/ext/repository/abstract.rb new file mode 100644 index 0000000..725c7c3 --- /dev/null +++ b/ext/repository/abstract.rb @@ -0,0 +1,12 @@ +Repository::Abstract.class_eval do + protected + + def synchronize_with_log_parsing!(revisions) + bulk_mode = revisions.size > 5 + returning(synchronize_without_log_parsing!(revisions)) do |changesets| + changesets.each(&:parse_log_and_update_tickets!) if bulk_mode + end + end + alias_method_chain :synchronize!, :log_parsing + +end \ No newline at end of file diff --git a/ext/ticket_change.rb b/ext/ticket_change.rb new file mode 100644 index 0000000..7288c37 --- /dev/null +++ b/ext/ticket_change.rb @@ -0,0 +1,33 @@ +#-- +# Copyright (c) 2009 Dimitrij Denissenko +# Please read LICENSE document for more information. +#++ +TicketChange.class_eval do + + def set_attributes_from_scm_reference(reference) + set_attribute_if_present!(:content, reference[:content]) + reference[:properties].each do |name, value| + set_attribute_from_scm_reference(name, value) + end + end + + protected + + def set_attribute_from_scm_reference(name, value) + case name + when /^assigned/, /^user/, 'u' + set_attribute_if_present! :assigned_user, User.identify(value) + when /^milestone/, 'm' + set_attribute_if_present! :milestone, project.milestones.active_on(ticket.created_at).find(:first, :conditions => ['LOWER(name) LIKE ?', value.downcase]) + when /^status/, 's' + set_attribute_if_present! :status, Status.find(:first, :conditions => ['LOWER(name) LIKE ?', value.downcase]) + when /^priority/, 'p' + set_attribute_if_present! :priority, Priority.find(:first, :conditions => ['LOWER(name) LIKE ?', value.downcase]) + end + end + + def set_attribute_if_present!(name, value) + send("#{name}=", value) if value.present? + end + +end \ No newline at end of file diff --git a/ext_info.rb b/ext_info.rb new file mode 100644 index 0000000..5078776 --- /dev/null +++ b/ext_info.rb @@ -0,0 +1,4 @@ +#-- +# Copyright (c) 2009 Dimitrij Denissenko +# Please read LICENSE document for more information. +#++ diff --git a/lib/repository/commit_log_parser.rb b/lib/repository/commit_log_parser.rb new file mode 100755 index 0000000..a85e1cc --- /dev/null +++ b/lib/repository/commit_log_parser.rb @@ -0,0 +1,56 @@ +#-- +# Copyright (c) 2009 +# Please read LICENSE document for more information. +#++ +class Repository::CommitLogParser + TICKET_REF = /\[\#(\d+)\]/ + + PROPERTY_KEY = /\w+/ + QUOTED_VALUE = /['"][^'"]+['"]/ + UNQUOTED_VALUE = /\w+/ + SEPARATOR = / *: */ + PROPERTY_ITEM = /(#{PROPERTY_KEY})#{SEPARATOR}(#{QUOTED_VALUE}|#{UNQUOTED_VALUE})/ + PROPERTY_BLOCK = /\(#{PROPERTY_ITEM}(?:[ ,]+#{PROPERTY_ITEM})*\)/ + + attr_reader :commit_id, :log + + def initialize(commit_id, log) + @commit_id = commit_id + @log = log.to_s + end + + # Yields a hash for each line which has a ticket reference + def each(&block) + log.each_line do |line| + parsed = parse_line(line) + yield parsed if parsed + end + end + + # Returns a hash of the id, properties and content (comment) + def parse_line(line) + line = line.gsub(TICKET_REF, '') + + ticket_id = $1.to_i + return nil if ticket_id.zero? + + properties = format_properties(line.scan(PROPERTY_BLOCK)) + return nil if properties.blank? + + { :id => ticket_id, :content => content(line.gsub(PROPERTY_BLOCK, '').squish), :properties => properties } + end + + protected + + def format_properties(properties) + properties = properties.flatten.map do |value| + value.gsub(/^['"]/, '').gsub(/['"]$/, '') + end + Hash[*properties] + end + + def content(content) + "[#{commit_id}] #{content.lstrip}".strip + end + +end diff --git a/spec/fixtures/changes.yml b/spec/fixtures/changes.yml new file mode 100644 index 0000000..be8d527 --- /dev/null +++ b/spec/fixtures/changes.yml @@ -0,0 +1,2 @@ +--- + \ No newline at end of file diff --git a/spec/fixtures/changesets.yml b/spec/fixtures/changesets.yml new file mode 100644 index 0000000..be8d527 --- /dev/null +++ b/spec/fixtures/changesets.yml @@ -0,0 +1,2 @@ +--- + \ No newline at end of file diff --git a/spec/fixtures/groups.yml b/spec/fixtures/groups.yml new file mode 100644 index 0000000..9f52cd9 --- /dev/null +++ b/spec/fixtures/groups.yml @@ -0,0 +1,10 @@ +Default: + id: 1 + name: Default + permissions: | + --- + tickets: + - create + - update + - view + - watch diff --git a/spec/fixtures/groups_projects.yml b/spec/fixtures/groups_projects.yml new file mode 100644 index 0000000..506e72b --- /dev/null +++ b/spec/fixtures/groups_projects.yml @@ -0,0 +1,3 @@ +retrospectiva_default: + project_id: 1 + group_id: 1 diff --git a/spec/fixtures/groups_users.yml b/spec/fixtures/groups_users.yml new file mode 100644 index 0000000..1aec8eb --- /dev/null +++ b/spec/fixtures/groups_users.yml @@ -0,0 +1,6 @@ +default_public: + user_id: 1 + group_id: 1 +default_agent: + user_id: 3 + group_id: 1 diff --git a/spec/fixtures/milestones.yml b/spec/fixtures/milestones.yml new file mode 100644 index 0000000..a45a993 --- /dev/null +++ b/spec/fixtures/milestones.yml @@ -0,0 +1,9 @@ +--- +next_release: + id: 1 + name: Next release + project_id: 1 + info: Long info + due: <%= 3.months.since.to_s(:db) %> + created_at: <%= 1.month.ago.to_s(:db) %> + updated_at: <%= 1.month.ago.to_s(:db) %> diff --git a/spec/fixtures/priorities.yml b/spec/fixtures/priorities.yml new file mode 100644 index 0000000..19cf809 --- /dev/null +++ b/spec/fixtures/priorities.yml @@ -0,0 +1,14 @@ +--- +normal: + name: Normal + id: 1 + rank: 2 + default_value: true +minor: + name: Minor + id: 2 + rank: 1 +major: + name: Major + id: 3 + rank: 3 diff --git a/spec/fixtures/projects.yml b/spec/fixtures/projects.yml new file mode 100644 index 0000000..a7843f5 --- /dev/null +++ b/spec/fixtures/projects.yml @@ -0,0 +1,8 @@ +--- +retro: + id: 1 + name: Retrospectiva + info: Retrospectiva project + closed: false + short_name: retrospectiva + repository_id: 1 diff --git a/spec/fixtures/repositories.yml b/spec/fixtures/repositories.yml new file mode 100644 index 0000000..15073bb --- /dev/null +++ b/spec/fixtures/repositories.yml @@ -0,0 +1,5 @@ +svn: + name: SVN repository + id: 1 + path: ../../tmp/svn_test + type: Repository::Subversion diff --git a/spec/fixtures/statuses.yml b/spec/fixtures/statuses.yml new file mode 100644 index 0000000..8ce8120 --- /dev/null +++ b/spec/fixtures/statuses.yml @@ -0,0 +1,25 @@ +open: + id: 1 + name: Open + rank: 1 + state_id: 1 + statement_id: 2 + default_value: true +assigned: + id: 2 + name: Assigned + rank: 2 + statement_id: 1 + state_id: 2 +invalid: + id: 3 + name: Invalid + rank: 3 + statement_id: 3 + state_id: 3 +fixed: + id: 4 + name: Fixed + rank: 4 + statement_id: 1 + state_id: 3 diff --git a/spec/fixtures/ticket_changes.yml b/spec/fixtures/ticket_changes.yml new file mode 100644 index 0000000..5813786 --- /dev/null +++ b/spec/fixtures/ticket_changes.yml @@ -0,0 +1 @@ +--- diff --git a/spec/fixtures/tickets.yml b/spec/fixtures/tickets.yml new file mode 100644 index 0000000..81e88fd --- /dev/null +++ b/spec/fixtures/tickets.yml @@ -0,0 +1,13 @@ +--- +open: + id: 1 + project_id: 1 + author: John Doe + priority_id: 1 + summary: An open ticket + content: Description + status_id: 1 + email: [email protected] + milestone_id: + created_at: <%= 4.months.ago.midnight.to_formatted_s(:db) %> + updated_at: <%= 4.months.ago.midnight.to_formatted_s(:db) %> diff --git a/spec/fixtures/users.yml b/spec/fixtures/users.yml new file mode 100644 index 0000000..9fca6de --- /dev/null +++ b/spec/fixtures/users.yml @@ -0,0 +1,20 @@ +--- +Public: + id: 1 + name: + admin: false + username: Public + password: fc0b88b7c9e2c896bcee4881d00d7bf5a7d2442d + email: + time_zone: London +agent: # plain_password = password + name: Agent + admin: false + id: 3 + password: b742714644f63a57f3bfe7dbe782451f0fe982b4 + salt: 987654 + username: agent + email: [email protected] + scm_name: agent + time_zone: London + private_key: 6b2c92007c38ca274ea45d8dd52f401b81ae44e6 diff --git a/spec/models/changeset_spec.rb b/spec/models/changeset_spec.rb new file mode 100644 index 0000000..c8734dc --- /dev/null +++ b/spec/models/changeset_spec.rb @@ -0,0 +1,46 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe Changeset do + fixtures :all + + def new_changeset(options = {}) + options.reverse_merge!(:revision => 'ABCDEFGH', :author => 'agent', :log => '[#1] Fixed Problem (s:fixed u:agent)') + repositories(:svn).changesets.create(options) + end + + it 'should create a valid changeset' do + changeset = new_changeset + changeset.should_not be_new_record + changeset.projects.should have(1).record + end + + describe 'after a new changeset was created' do + + it 'should update the tickets' do + new_changeset + tickets(:open).status.should == statuses(:fixed) + tickets(:open).assigned_user.should == users(:agent) + end + + it 'should NOT update tickets if author cannot be found' do + new_changeset(:author => 'noone') + tickets(:open).status.should == statuses(:open) + tickets(:open).assigned_user.should be_nil + end + + it 'should NOT update tickets if tickets cannot be found' do + new_changeset(:log => '[#99] Fixed Problem (s:fixed u:agent)') + tickets(:open).status.should == statuses(:open) + tickets(:open).assigned_user.should be_nil + end + + it 'should NOT update tickets if user has no permission to do so' do + groups(:Default).update_attribute(:permissions, {}) + tickets(:open).status.should == statuses(:open) + tickets(:open).assigned_user.should be_nil + end + + end + + +end \ No newline at end of file diff --git a/spec/models/commit_log_parser_spec.rb b/spec/models/commit_log_parser_spec.rb new file mode 100644 index 0000000..7cde936 --- /dev/null +++ b/spec/models/commit_log_parser_spec.rb @@ -0,0 +1,54 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe Repository::CommitLogParser do + def parse(line) + result = [] + Repository::CommitLogParser.new('REVABC', line).each do |parsed| + result << parsed + end + result + end + + it 'should ignore lines without a ticket reference' do + parse("(status:fixed assigned:mabs) fixed a little bug").should == [] + end + + it 'should ignore lines without property changes' do + parse("[#1234] fixed a little bug").should == [] + end + + it 'should correctly parse pre-commit lines' do + parse("[#1234](status:fixed assigned:mabs) fixed a little bug").should == [ + :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + ] + end + + it 'should correctly parse split-commit lines' do + parse("[#1234] fixed a little bug (status:fixed assigned:mabs)").should == [ + :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + ] + end + + it 'should correctly parse post-commit lines' do + parse("fixed a little bug [#1234] (status:fixed assigned:mabs)").should == [ + :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + ] + end + + it 'should correctly parse lines with lots of whitespaces' do + parse(" [#1234] fixed a little bug (status:fixed assigned:mabs) ").should == [ + :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + ] + end + + it 'should correctly parse unusual property patterns' do + parse("[#1234] fixed a little bug (status : \"fixed\" , assigned : mabs)").should == [ + :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + ] + + parse("fixed a little bug [#1234] (status : \"fixed\" assigned :mabs)").should == [ + :id => 1234, :content => '[REVABC] fixed a little bug', :properties => { 'status' => 'fixed', 'assigned' => 'mabs' } + ] + end + +end \ No newline at end of file diff --git a/spec/models/repository/abstract_spec.rb b/spec/models/repository/abstract_spec.rb new file mode 100644 index 0000000..38e3b81 --- /dev/null +++ b/spec/models/repository/abstract_spec.rb @@ -0,0 +1,25 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe Repository::Abstract do + fixtures :all + + before do + @repository = repositories(:svn) + end + + describe 'bulk synchronization' do + + it 'should update the tickets after the synchronisation' do + @changeset = mock_model(Changeset) + @repository.should_receive(:synchronize_without_log_parsing!).and_return([@changeset]) + @changeset.should_receive(:parse_log_and_update_tickets!) + @repository.sync_changesets + end + + it 'should perform correctly' do + @repository.sync_changesets + @repository.changesets.should have(10).records + end + + end +end \ No newline at end of file diff --git a/spec/models/ticket_change_spec.rb b/spec/models/ticket_change_spec.rb new file mode 100644 index 0000000..2e0664f --- /dev/null +++ b/spec/models/ticket_change_spec.rb @@ -0,0 +1,127 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe TicketChange do + fixtures :all + + before do + @ticket = tickets(:open) + @change = @ticket.changes.new + end + + describe 'updating content' do + + it 'should update' do + @change.set_attributes_from_scm_reference(:properties => {}, :content => 'Fixed Bug') + @change.content.should == 'Fixed Bug' + end + + it 'should not update if not present' do + @change.set_attributes_from_scm_reference(:properties => {}, :content => '') + @change.content.should be_nil + end + + end + + describe 'updating assigned user' do + + it 'should update by username' do + @change.set_attributes_from_scm_reference(:properties => { 'user' => 'agent' }) + @change.assigned_user.should == users(:agent) + end + + it 'should update by email' do + @change.set_attributes_from_scm_reference(:properties => { 'user' => '[email protected]' }) + @change.assigned_user.should == users(:agent) + end + + it 'should update by alternative key' do + @change.set_attributes_from_scm_reference(:properties => { 'assigned' => 'agent' }) + @change.assigned_user.should == users(:agent) + end + + it 'should update by short key' do + @change.set_attributes_from_scm_reference(:properties => { 'u' => 'agent' }) + @change.assigned_user.should == users(:agent) + end + + it 'should not update if user cannot be found' do + @change.set_attributes_from_scm_reference(:properties => { 'user' => 'me' }) + @change.assigned_user.should be_nil + end + + end + + describe 'updating milestone' do + + it 'should update by name' do + @change.set_attributes_from_scm_reference(:properties => { 'milestone' => 'next release' }) + @change.milestone.should == milestones(:next_release) + end + + it 'should update by name (case insensitive)' do + @change.set_attributes_from_scm_reference(:properties => { 'milestone' => 'Next Release' }) + @change.milestone.should == milestones(:next_release) + end + + it 'should update via shortcut' do + @change.set_attributes_from_scm_reference(:properties => { 'm' => 'Next Release' }) + @change.milestone.should == milestones(:next_release) + end + + it 'should not update if milestone cannot be found' do + @change.set_attributes_from_scm_reference(:properties => { 'milestone' => 'invalid' }) + @change.milestone.should be_nil + end + + end + + describe 'updating status' do + + it 'should update by name' do + @change.set_attributes_from_scm_reference(:properties => { 'status' => 'fixed' }) + @change.status.should == statuses(:fixed) + end + + it 'should update by name (case insensitive)' do + @change.set_attributes_from_scm_reference(:properties => { 'status' => 'FIXED' }) + @change.status.should == statuses(:fixed) + end + + it 'should update via shortcut' do + @change.set_attributes_from_scm_reference(:properties => { 's' => 'fixed' }) + @change.status.should == statuses(:fixed) + end + + it 'should not update if status cannot be found' do + @change.set_attributes_from_scm_reference(:properties => { 'status' => 'accomplished' }) + @change.status.should == statuses(:open) + end + + end + + describe 'updating priority' do + + it 'should update by name' do + @change.set_attributes_from_scm_reference(:properties => { 'priority' => 'major' }) + @change.priority.should == priorities(:major) + end + + it 'should update by name (case insensitive)' do + @change.set_attributes_from_scm_reference(:properties => { 'priority' => 'MAJOR' }) + @change.priority.should == priorities(:major) + end + + it 'should update via shortcut' do + @change.set_attributes_from_scm_reference(:properties => { 'p' => 'major' }) + @change.priority.should == priorities(:major) + end + + it 'should not update if priority cannot be found' do + @change.set_attributes_from_scm_reference(:properties => { 'priority' => 'invalid' }) + @change.priority.should == priorities(:normal) + end + + end + + +end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..54d00ea --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,6 @@ +ENV['RETRO_EXT'] ||= File.basename(File.expand_path(File.dirname(__FILE__) + '/..')) +require File.expand_path(File.dirname(__FILE__) + '/../../../spec/spec_helper') + +Spec::Runner.configure do |config| + config.fixture_path = File.dirname(__FILE__) + '/fixtures/' +end
openscriptures/openscriptures
da6ba3932b34287325f10e71ce34104e8a0ba03a
Initial move of django code from svn to git
diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..f576755 --- /dev/null +++ b/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +perl -e 'print scalar(localtime) . "\n"' + +python manage.py reset core --noinput +python manage.py syncdb +#If exists data/supplemental_data.sql, then import the data +cd data/manuscripts +python import.py +#python merge.py + +perl -e 'print scalar(localtime) . "\n"' \ No newline at end of file diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/admin.py b/core/admin.py new file mode 100644 index 0000000..ae264c8 --- /dev/null +++ b/core/admin.py @@ -0,0 +1,6 @@ +from openscriptures.core.models import Language +from openscriptures.core.models import Work +from django.contrib import admin + +admin.site.register(Language) +admin.site.register(Work) diff --git a/core/models.py b/core/models.py new file mode 100644 index 0000000..068554f --- /dev/null +++ b/core/models.py @@ -0,0 +1,340 @@ +# encoding: utf-8 + +from django.db import models +from django.db.models import Q + +OSIS_BIBLE_BOOK_CODES = ( + #Gen Exod Lev Num Deut Josh Judg Ruth 1Sam 2Sam 1Kgs 2Kgs 1Chr 2Chr Ezra Neh Esth Job Ps Prov Eccl Song Isa Jer Lam Ezek Dan Hos Joel Amos Obad Jonah Mic Nah Hab Zeph Hag Zech Mal + #'Matt', 'Mark', 'Luke', 'John', 'Acts', 'Rom', '1Cor', '2Cor', 'Gal', 'Eph', 'Phil', 'Col', '1Thess', '2Thess', '1Tim', '2Tim', 'Titus', 'Phlm', 'Heb', 'Jas', '1Pet', '2Pet', '1John', '2John', '3John', 'Jude', 'Rev' + #'Luke' + #'Luke', + #'Acts' + #'1John', + #'Phil', + #'2John', + #'3John', + 'John' +# 'Jude' +#'John', +) + +OSIS_BOOK_NAMES = { + "Gen": "Genesis", + "Exod": "Exodus", + "Lev": "Leviticus", + "Num": "Numbers", + "Deut": "Deuteronomy", + "Josh": "Joshua", + "Judg": "Judges", + "Ruth": "Ruth", + "1Sam": "1 Samuel", + "2Sam": "2 Samuel", + "1Kgs": "1 Kings", + "2Kgs": "2 Kings", + "1Chr": "1 Chronicles", + "2Chr": "2 Chronicles", + "Ezra": "Ezra", + "Neh": "Nehemiah", + "Esth": "Esther", + "Job": "Job", + "Ps": "Psalms", + "Prov": "Proverbs", + "Eccl": "Ecclesiastes", + "Song": "Song of Solomon", + "Isa": "Isaiah", + "Jer": "Jeremiah", + "Lam": "Lamentations", + "Ezek": "Ezekiel", + "Dan": "Daniel", + "Hos": "Hosea", + "Joel": "Joel", + "Amos": "Amos", + "Obad": "Obadiah", + "Jonah": "Jonah", + "Mic": "Micah", + "Nah": "Nahum", + "Hab": "Habakkuk", + "Zeph": "Zephaniah", + "Hag": "Haggai", + "Zech": "Zechariah", + "Mal": "Malachi", + + "Matt": "Matthew", + "Mark": "Mark", + "Luke": "Luke", + "John": "John", + "Acts": "Acts", + "Rom": "Romans", + "1Cor": "1 Corinthians", + "2Cor": "2 Corinthians", + "Gal": "Galatians", + "Eph": "Ephesians", + "Phil": "Philippians", + "Col": "Colossians", + "1Thess": "1 Thessalonians", + "2Thess": "2 Thessalonians", + "1Tim": "1 Timothy", + "2Tim": "2 Timothy", + "Titus": "Titus", + "Phlm": "Philemon", + "Heb": "Hebrews", + "Jas": "James", + "1Pet": "1 Peter", + "2Pet": "2 Peter", + "1John": "1 John", + "2John": "2 John", + "3John": "3 John", + "Jude": "Jude", + "Rev": "Revelation", + + "Bar": "Baruch", + "AddDan": "Additions to Daniel", + "PrAzar": "Prayer of Azariah", + "Bel": "Bel and the Dragon", + "SgThree": "Song of the Three Young Men", + "Sus": "Susanna", + "1Esd": "1 Esdras", + "2Esd": "2 Esdras", + "AddEsth": "Additions to Esther", + "EpJer": "Epistle of Jeremiah", + "Jdt": "Judith", + "1Macc": "1 Maccabees", + "2Macc": "2 Maccabees", + "3Macc": "3 Maccabees", + "4Macc": "4 Maccabees", + "PrMan": "Prayer of Manasseh", + "Sir": "Sirach/Ecclesiasticus", + "Tob": "Tobit", + "Wis": "Wisdom of Solomon" +} + +# Todo: We need to figure out a better way to do ENUM + +class Language(models.Model): + "A human language, either ancient or modern." + + DIRECTIONS = ( + ('ltr', 'Left to Right'), + ('rtl', 'Right to Left'), + #also needing vertical directions, see CSS writing-mode + ) + + code = models.CharField("ISO language code", max_length=10, primary_key=True) + name = models.CharField(max_length=32) #name = models.ForeignKey('Text', related_name='language_name_set') #Reverse query name for field 'name' clashes with field 'Text.language'. Add a related_name argument to the definition for 'name'. + direction = models.CharField("Text directionality", max_length=3, choices=DIRECTIONS, default='ltr') + + def __unicode__(self): + return self.name + + +#class Text(models.Model): +# "A i18n construct. Used throughout the schema to store text." +# +# id = models.AutoField(primary_key=True) #this should eventually be primary_key together with language +# language = models.ForeignKey('Language') +# data = models.TextField() +# +# def __unicode__(self): +# return self.data + + +class License(models.Model): + "A license that a work uses to indicate the copyright restrictions or permissions." + + name = models.CharField(max_length=128) #name = models.ForeignKey(Text, related_name='license_name_set') + abbreviation = models.CharField(max_length=32, null=True) #abbreviation = models.ForeignKey(Text, null=True) + url = models.URLField(null=True, help_text="Primary URL which defines and describes the license.") + + isolatable = models.BooleanField(default=True, help_text="If this is true, then this work can be displayed independently. Otherwise, it must only be displayed in conjunction with other works. Important condition for fair use license.") + + def __unicode__(self): + return self.name + + +class Work(models.Model): + """ + Represents an OSIS work. May be the Bible, a book of the Bible, an edition + of the Bible, a non-biblical work such as the Qur'an or the Mishnah. + """ + + title = models.CharField(max_length=255) #title = models.ForeignKey(Text, related_name='work_title_set') + abbreviation = models.CharField(max_length=255, null=True) #abbreviation = models.ForeignKey(Text, null=True) + description = models.TextField(null=True) + url = models.URLField(null=True) + + ORIGINALITIES = ( + ('autograph', 'Autograph'), + ('manuscript', 'Manuscript'), + ('unified', 'Unified Work'), + ('manuscript-edition', 'Manuscript Edition'), + ('translation', 'Translation') + ) + originality = models.CharField(max_length=32, choices=ORIGINALITIES, null=True, help_text="If NULL, then inherited from parent") + + TYPES = ( + ('Bible', "Bible"), + ('Lexicon', 'Lexicon') + ) + type = models.CharField(max_length=16, choices=TYPES, null=True, help_text="If NULL, then inherited from parent") #If NULL, then inherited from parent + language = models.ForeignKey(Language, null=True, help_text="If NULL, then inherited from parent") #If NULL, then inherited from parent + osis_slug = models.SlugField(max_length=255, help_text="OSIS identifier which should correspond to the abbreviation, like NIV, ESV, or KJV") + #TODO: Needing edition and version? + publish_date = models.DateField(null=True, help_text="When the work was published; if NULL, then inherited from parent") + + #returns Bible.en.NIV.1984, which is an osisID Prefix + # Note: This is bad because it is not indexable + def __getattr__(self, name): + if name == 'osis_id': + osis_id = [] + if self.type: + osis_id.append(self.type) + if self.language: + osis_id.append(self.language) + if self.osis_slug: + osis_id.append(self.osis_slug) + if self.publish_date: + osis_id.append(self.publish_date.year) + return ".".join(osis_id) + else: + raise AttributeError("The property %s does not exist" % name) + + base = models.ForeignKey('self', null=True, related_name="variants", help_text="If variant_number is not null, then 'base' is the work that contains this work's tokens where tokens.variant_number = self.variant_number") + + creator = models.TextField(null=True) #models.ForeignKey(Text, related_name='work_creator_set') + copyright = models.TextField(null=True) #models.ForeignKey(Text, related_name='work_copyright_set') + license = models.ForeignKey(License) + + unified = models.ForeignKey('self', null=True, verbose_name="Work which this work has been merged into") + + def __unicode__(self): + return self.title + +class VariantGroup(models.Model): + work = models.ForeignKey(Work, help_text="The work which this variant group is associated with. If it is different from the token's work, then this variant group contains the tokens that are unique to that work.") #If set, it can either be the same as the base work, or a work that itself has a base the title and description should be left empty; otherwise, then this variant group is not associated with any work, and the title and description can be provided if applicable. + primacy = models.PositiveSmallIntegerField(null=False, default=0, help_text="A value of zero means that the tokens assigned to this token group are considered the most preeminent (i.e. they are displayed as the base text). Primacy values above zero indicate subordinate readings. The higher the number, the less precedence a token it has in relation to other token groups.") + title = models.CharField(max_length=255, null=True) + description = models.TextField(null=True) + license = models.ForeignKey(License, null=True, help_text="If not specified, license is inherited from the work's license.") + + #class Meta: + # unique_together = (('work', 'primacy'),) #This may not be helpful + +class VariantGroupToken(models.Model): + "The many-to-many relationship between Token and VariantGroup goes through this model." + token = models.ForeignKey('Token') + variant_group = models.ForeignKey('VariantGroup') + + certainty = models.PositiveSmallIntegerField(default=0, null=False, help_text="Serves to indicate whether a token should be set apart with brackets, that is, if it is a less certain reading. The most certain readings are '0' (default). The number here corresponds to the number of square brackets that set apart this token. Overrides Token.certainty.") + +class Token(models.Model): + MORPHEME = 1 + WORD = 2 + PUNCTUATION = 3 + WHITESPACE = 4 + + TYPES = ( + (MORPHEME, 'Morpheme'), + (WORD, 'Word'), + #(PHRASE, 'Phrase'), + (PUNCTUATION, 'Punctuation'), + (WHITESPACE, 'Whitespace'), + ) + + data = models.CharField(max_length=255, db_index=True) + type = models.PositiveSmallIntegerField(choices=TYPES, default=WORD, db_index=True, help_text="Morphemes do not automatically get whitespace padding, words do (TENTATIVE).") + position = models.PositiveIntegerField(db_index=True) + certainty = models.PositiveSmallIntegerField(default=0, null=True, help_text="Serves to indicate whether a token should be set apart with brackets, that is, if it is a less certain reading. The most certain readings are '0' (default). The number here corresponds to the number of square brackets that set apart this token. Overridden by VariantGroupToken.certainty (in that case, self.certainty may be None)") + unified_token = models.ForeignKey('self', null=True, help_text="The token in the merged/unified work that represents this token. unified_token.originality should be 'unified'") + work = models.ForeignKey(Work) + #variant_group = models.ForeignKey(VariantGroup, null=True, help_text="The grouping of variants that this token belongs to; if empty, token is common to all variant groups associated with this token's work, including all tokens of all works that point to this token's work as their base.") + variant_groups = models.ManyToManyField(VariantGroup, through=VariantGroupToken, null=True, help_text="The groupings of variants (associated with this work or its sub-works) that this token belongs to; if none provided, then token is common to all variant groups associated with this token's work, including all tokens of all works that point to this token's work as their base.") + + class Meta: + ordering = ['position'] #, 'variant_number' + #Note: This unique constraint is removed due to the fact that in MySQL, the default utf8 collation means "Και" and "καὶ" are equivalent + #unique_together = ( + # ('data', 'position', 'work'), + #) + + cmp_data = None + def __unicode__(self): + if(self.cmp_data): + return self.cmp_data + return ('[' * self.certainty) + self.data + (']' * self.certainty) + + def __hash__(self): + return hash(unicode(self)) + + def __eq__(self, other): + return unicode(self) == unicode(other) + +#class NormalizedToken(Token): +# class Meta: +# proxy = True + + +class TokenParsing(models.Model): + "This is a temporary construct until language-specific parsing models are constructed." + token = models.ForeignKey(Token, related_name='token_parsing_set') + raw = models.CharField(max_length=255, help_text="All parsing information provided verbatim") + parse = models.CharField(max_length=255, help_text="A string consisting of whatever the work provides; the unparsed parsing. Likely consisting of the lemma, Strong's number, morph, etc. This is temporary until we can integrate with lemma lattice. Temporary measure until Lemma Lattice released") + strongs = models.CharField(max_length=255, help_text="The strongs number, prefixed by 'H' or 'G' specifying whether it is for the Hebrew or Greek, respectively. Multiple numbers separated by semicolon. Temporary measure until Lemma Lattice released.") + lemma = models.CharField(max_length=255, help_text="The lemma chosen for this token. Need not be supplied if strongs given. If multiple lemmas are provided, then separate with semicolon. Temporary measure until Lemma Lattice released") + language = models.ForeignKey(Language) + work = models.ForeignKey(Work, null=True, help_text="The work that defines this parsing; may be null since a user may provide it. Usually same as token.work") + +class Ref(models.Model): + BOOK_GROUP = 1 + BOOK = 2 + MAJOR_SECTION = 3 + SECTION = 4 + PARAGRAPH = 5 + CHAPTER = 6 + VERSE = 7 + PAGE = 8 + + TYPES = ( + (BOOK_GROUP, 'bookGroup'), + (BOOK, 'book'), + (MAJOR_SECTION, 'majorSection'), + (SECTION, 'section'), + (PARAGRAPH, 'paragraph'), + (CHAPTER, 'chapter'), + (VERSE, 'verse'), + (PAGE, 'page') + ) + + work = models.ForeignKey(Work, null=True, help_text="If this ref is for a work that relies on a base work, this value does not point to the base work; that is, if two works are merged together, with one being the base work, then each work has its own references stored, and they refer to their respective works, not the base work.") + type = models.PositiveSmallIntegerField(choices=TYPES) + osis_id = models.CharField(max_length=50, db_index=True) + position = models.PositiveIntegerField(db_index=True) + title = models.CharField(max_length=50) + parent = models.ForeignKey('self', null=True) + start_token = models.ForeignKey(Token, related_name='start_token_ref_set') #, help_text="This can be null for convienence while creating objects, but it should not end up being null." + end_token = models.ForeignKey(Token, null=True, related_name='end_token_ref_set') + numerical_start = models.PositiveIntegerField(null=True) + numerical_end = models.PositiveIntegerField(null=True) + + def get_tokens(self, variant_number = 1): + return Token.objects.filter( + Q(variant_number = None) | Q(variant_number = variant_number), + work = self.work, + position__gte = self.start_token.position, + position__lte = self.end_token.position + ) + tokens = property(get_tokens) + + def __hash__(self): + return hash(unicode(self)) + + def __eq__(self, other): + return unicode(self) == unicode(other) + + def __unicode__(self): + if self.type == Ref.PAGE: + if not self.numerical_end or self.numerical_end == self.numerical_start: + return "p. " + self.numerical_start + else: + return "pp. " + self.numerical_start + "-" + self.numerical_end + return self.osis_id + diff --git a/core/views.py b/core/views.py new file mode 100644 index 0000000..8479d78 --- /dev/null +++ b/core/views.py @@ -0,0 +1,25 @@ +from django.shortcuts import render_to_response +from models import * +import datetime +from django.template.loader import get_template +from django.template import Context +from django.http import HttpResponse + + +from django.http import HttpResponse + +def index(request): + now = datetime.datetime.now() + return HttpResponse("Hello, world. This is the index. %s" % now) + +def hello(request, name): + #datetime.timedelta(hours=params['name']) + #return HttpResponse("Hello %s" % params['name']) + meta_values = request.META.items() + meta_values.sort() + + #t = get_template('hello.html') + #html = t.render(Context(params)) + #return HttpResponse(html) + return render_to_response('hello.html', locals()) + diff --git a/data/__init__.py b/data/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/data/dump_supplemental_data.sh b/data/dump_supplemental_data.sh new file mode 100755 index 0000000..2505996 --- /dev/null +++ b/data/dump_supplemental_data.sh @@ -0,0 +1,2 @@ + +mysqldump -u root -p --no-create-info --compact --skip-add-drop-table --databases oss_core --tables core_ref core_token core_tokenparsing core_work > supplemental_data.sql \ No newline at end of file diff --git a/data/import_helpers.py b/data/import_helpers.py new file mode 100644 index 0000000..fc2b374 --- /dev/null +++ b/data/import_helpers.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# encoding: utf-8 + +import re, unicodedata, os, urllib, sys +from openscriptures.core.models import * + +def normalize_token(data): + "Normalize to Unicode NFC, strip out all diacritics, apostrophies, and make lower-case." + # credit: http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string + data = unicodedata.normalize('NFC', ''.join((c for c in unicodedata.normalize('NFD', data) if unicodedata.category(c) != 'Mn')).lower()) + data = data.replace(r'\s+', ' ') + #data = re.sub(ur"['’]", '', data) + data = data.replace(u"'", '') + data = data.replace(u"’", '') + return data + +def download_resource(source_url): + "Download the file in the provided URL if it does not already exist in the working directory." + if(not os.path.exists(os.path.basename(source_url))): + if(not os.path.exists(os.path.basename(source_url))): + print "Downloading " + source_url + urllib.urlretrieve(source_url, os.path.basename(source_url)) + + +def abort_if_imported(workID): + "Shortcut see if the provided work ID already exists in the system; if so, then abort unless --force command line argument is supplied" + if(len(Work.objects.filter(id=workID)) and not (len(sys.argv)>1 and sys.argv[1] == '--force')): + print " (already imported; pass --force option to delete existing work and reimport)" + exit() + +def delete_work(msID, *varMsIDs): + "Deletes a work without a greedy cascade" + tokens = Token.objects.filter(work=msID) + for token in tokens: + token.variant_groups.clear() + tokens.update(unified_token=None) + + for varMsID in varMsIDs: + #VariantGroupToken.objects.filter(work=varMsID).update() + # delete all VariantGroupTokens which are associated with + #VariantGroup.objects.filter(work=varMsID).delete() + Work.objects.filter(id=varMsID).update(unified=None, base=None) + Work.objects.filter(id=varMsID).delete() + + VariantGroup.objects.filter(work=msID).delete() + Work.objects.filter(id=msID).update(unified=None) + Work.objects.filter(id=msID).delete() \ No newline at end of file diff --git a/data/initial_data.json b/data/initial_data.json new file mode 100644 index 0000000..d56c394 --- /dev/null +++ b/data/initial_data.json @@ -0,0 +1,130 @@ +[ + { + "model": "core.language", + "pk": "en", + "fields": { + "name": "English", + "direction": "ltr" + } + }, + { + "model": "core.language", + "pk": "hbo", + "fields": { + "name": "Hebrew", + "direction": "rtl" + } + }, + { + "model": "core.language", + "pk": "oar", + "fields": { + "name": "Aramaic", + "direction": "rtl" + } + }, + { + "model": "core.language", + "pk": "grc", + "fields": { + "name": "Greek", + "direction": "ltr" + } + }, + + + + { + "model": "core.license", + "pk": 1, + "fields": { + "name": "Public Domain", + "abbreviation": "PD", + "url": "http://creativecommons.org/licenses/publicdomain/" + } + }, + { + "model": "core.license", + "pk": 2, + "fields": { + "name": "Creative Commons Attribution 3.0", + "abbreviation": "CC-BY-3.0", + "url": "http://creativecommons.org/licenses/by/3.0/" + } + }, + { + "model": "core.license", + "pk": 3, + "fields": { + "name": "Creative Commons Attribution-No Derivative Works 3.0", + "abbreviation": "CC-BY-ND-3.0", + "url": "http://creativecommons.org/licenses/by-nd/3.0/" + } + }, + { + "model": "core.license", + "pk": 4, + "fields": { + "name": "Creative Commons Attribution-Noncommercial-No Derivative Works 3.0", + "abbreviation": "CC-BY-NC-ND-3.0", + "url": "http://creativecommons.org/licenses/by-nc-nd/3.0/" + } + }, + { + "model": "core.license", + "pk": 5, + "fields": { + "name": "Creative Commons Attribution-Noncommercial 3.0", + "abbreviation": "CC-BY-NC-3.0", + "url": "http://creativecommons.org/licenses/by-nc/3.0/" + } + }, + { + "model": "core.license", + "pk": 6, + "fields": { + "name": "Creative Commons Attribution-Noncommercial-Share Alike 3.0", + "abbreviation": "CC-BY-NC-SA-3.0", + "url": "http://creativecommons.org/licenses/by-nc-sa/3.0/" + } + }, + { + "model": "core.license", + "pk": 7, + "fields": { + "name": "Creative Commons Attribution-Share Alike 3.0", + "abbreviation": "CC-BY-SA-3.0", + "url": "http://creativecommons.org/licenses/by-sa/3.0/" + } + }, + { + "model": "core.license", + "pk": 8, + "fields": { + "name": "MIT License", + "abbreviation": "CC-BY-SA-3.0", + "url": "http://creativecommons.org/licenses/MIT/" + } + }, + { + "model": "core.license", + "pk": 9, + "fields": { + "name": "GNU Free Documentation License", + "abbreviation": "GFDL", + "url": "http://www.gnu.org/copyleft/fdl.html" + } + }, + { + "model": "core.license", + "pk": 10, + "fields": { + "name": "Fair Use", + "isolatable" : false, + "url": "http://en.wikipedia.org/wiki/Fair_use" + } + } + + + +] diff --git a/data/manuscripts/TNT.py b/data/manuscripts/TNT.py new file mode 100644 index 0000000..cdb495a --- /dev/null +++ b/data/manuscripts/TNT.py @@ -0,0 +1,959 @@ +#!/usr/bin/env python +# encoding: utf-8 +""" +Problem: if two of the same words occur together in the original, this will be lost! +""" + +TNT1_ID = 10 #TNT +TNT2_ID = 11 #TNT2 + +import sys, os, re, unicodedata, difflib, zipfile, StringIO +from datetime import date +from django.core.management import setup_environ +from django.utils.encoding import smart_str, smart_unicode +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) #There's probably a better way of doing this +from openscriptures import settings +setup_environ(settings) +from openscriptures.core.models import * +from openscriptures.data import import_helpers + +# Abort if MS has already been added (or --force not supplied) +import_helpers.abort_if_imported(TNT1_ID) + +# Download the source file +source_url = "http://www.tyndalehouse.com/Download/TNT 1.0.0.zip" +var_source_url = "http://www.tyndalehouse.com/Download/TNT2 1.0.0.zip" +#import_helpers.download_resource(source_url) +#import_helpers.download_resource(var_source_url) + +# Delete existing works and their contents +import_helpers.delete_work(TNT1_ID, TNT2_ID) + +workTNT1 = Work( + id = TNT1_ID, + title = "Tregelles' Greek New Testament", + abbreviation = 'Tregelles', + language = Language('grc'), + type = 'Bible', + osis_slug = 'TNT', + publish_date = date(1879, 1, 1), + originality = 'manuscript-edition', + creator = "Samuel Prideaux Tregelles, LL.D. Transcription edited by Dirk Jongkind, in collaboration with Julie Woodson, Natacha Pfister, and Robert Crellin. Consultant editor: P.J. Williams. Tyndale House.", + url = source_url, + #variant_number = 1, + license = License.objects.get(url="http://creativecommons.org/licenses/by-nc-sa/3.0/") +) +workTNT1.save() + +varGroupTNT1 = VariantGroup( + work = workTNT1, + primacy = 0 +) +varGroupTNT1.save() + +varGroupTNT1_Steph = VariantGroup( + work = workTNT1, + title = "Stephanus", + primacy = 1 +) +varGroupTNT1_Steph.save() + +varGroupTNT1_D = VariantGroup( + work = workTNT1, + title = "Codex D", + primacy = 1 +) +varGroupTNT1_D.save() + +# The variant work is the corrected edition +workTNT2 = Work( + id = TNT2_ID, + title = "Tregelles' Corrected Greek New Testament", + abbreviation = "Tregelles2", + language = Language('grc'), + type = 'Bible', + osis_slug = 'Tregelles2', + publish_date = date(2009, 6, 1), + originality = 'manuscript-edition', + creator = "Samuel Prideaux Tregelles, LL.D. Transcription edited by Dirk Jongkind, in collaboration with Julie Woodson, Natacha Pfister, and Robert Crellin. Consultant editor: P.J. Williams. Tyndale House.", + url = var_source_url, + base = workTNT1, + #variant_number = 2, + license = License.objects.get(url="http://en.wikipedia.org/wiki/Fair_use") +) +workTNT2.save() + +varGroupTNT2 = VariantGroup( + work = workTNT2, + primacy = 0 +) +varGroupTNT2.save() + +varGroupTNT2_Steph = VariantGroup( + work = workTNT2, + title = "Stephanus", + primacy = 1 +) +varGroupTNT2_Steph.save() + +varGroupTNT2_D = VariantGroup( + work = workTNT2, + title = "Codex D", + primacy = 1 +) +varGroupTNT2_D.save() + + +""" +What is included are the page-numbers of the print edition, the section and +paragraph breaks (in the printed edition the former are marked by a blank line, +the latter by simple indentation of the first line of the paragraph), the +punctuation of the text, and the accentuation as given by Tregelles. The title +and subscription at the end of each book are also included. +""" + +""" http://www.tyndalehouse.com/tregelles/page2.html: +The Greek New Testament, +Edited from Ancient Authorities, with their +Various Readings in Full, +and the +Latin Version of Jerome, + +by Samuel Prideaux Tregelles, LL.D. + +London. +Samuel Bagster and Sons: Paternoster Row. +C. J. Stewart: King William Street, West Strand. +1857–1879. + +Transcription edited by Dirk Jongkind, in collaboration with Julie Woodson, Natacha Pfister, and Robert Crellin. Consultant editor: P.J. Williams + +Tyndale House, Cambridge +2009. +""" + + + + +TNT_TO_OSIS_BOOK_CODES = { +"Mat": 'Matt', +"Mark": 'Mark', +"Luke": 'Luke', +"John": 'John', +"Acts": 'Acts', +"Rom": 'Rom', +"1Co": '1Cor', +"2Co": '2Cor', +"Gal": 'Gal', +"Eph": 'Eph', +"Phi": 'Phil', +"Col": 'Col', +"1Th": '1Thess', +"2Th": '2Thess', +"1Ti": '1Tim', +"2Ti": '2Tim', +"Tit": 'Titus', +"Phm": 'Phlm', +"Heb": 'Heb', +"Jas": 'Jas', +"1Pet": '1Pet', +"2Pet": '2Pet', +"1John":'1John', +"2John":'2John', +"3John":'3John', +"Jude": 'Jude', +"Rev": 'Rev' +} + + +reVerseMarker = re.compile(ur"^\$\$\$(?P<book>\w+)\.(?P<chapter>\d+)\.(?P<verse>\d+)", re.VERBOSE) + + +# Notice: The two works have different reference systems (Mat 23:13), thus we +# need to store separate sets of references, one assigned to TNT1 and the other +# to TNT2; TNT2 would be a variant of TNT1, but instead of inheriting TNT1's +# reference system, TNT2's would be used instead... though both systems would +# refer to the same tokens; this is preferrable to making both TNT1 and TNT2 a +# top level base work because then there would be much duplication and +# furthermore the variant distinctions based solely on diacritics (everything) +# would be lost. +# +# So we have TNT1 and TNT2, and in each of these we have Steph and D, but Steph +# and D don't match up exactly in both So we basically need to have TNT1 as +# base, with TNT2 as derivative work (variant group 2) And then we need Steph +# and D to be variant group sets (2,3), with Steph2 and D2 as Variant group sets +# (3,4)?? How would Steph2 be based on Steph? This is getting too convoluted? +# Unless we merge everything together as originally talked about, and where +# everything agrees we insert a token without a variant group association. But +# if any token is not agreed to by all of the variant groups, then the tokens +# for each variant group must be stored separately (in duplicates) however they +# all share the same position. But is there any way to determine that they are +# duplicates other than by comparing the actual string values? Overwhelmingly +# the tokens will be overlap so there will be fewer tokens stored, and this will +# improve performance and storage space, and will give fewer tokens to be +# linked, but how exactly will such a work be merged with other works? It isn't +# possible to just display one variant group at a time, is it? + +files = ( + open("TNT 1.0.0.txt"), + open("TNT2 1.0.0.txt") +) + +verseMeta = [None, None] +verseBuffer = ["", ""] +rawVerses = [] +lineNumber = [0, 0] +for f in files: + rawVerses.append([]) + +print "Parsing all of the verses out of the files..." + +while True: + for i in range(0,len(files)): + if files[i].closed: + continue + line = files[i].readline() + if not line: + files[i].close() + continue + lineNumber[i] += 1 + #line = line.strip() + if not line: #skip blank line + continue + line = unicodedata.normalize("NFC", smart_unicode(line)) + line = line.lstrip(ur"\uFEFF") #REMOVE ZWNB/BOM + line = line.rstrip() + #line = re.sub(r"\r?\n$", '', line) + line = re.sub(ur'<PΒ>', '<PB>', line) #Fix error in $$$Mat.26.55 (Greek B used instead of Latin B) + line = re.sub(ur'([^> ]+)(<Page.*?>)([^< ]+)', r'\1\3\2', line) #Ensure that Page refs don't break up words: ἔδη<Page = 477>σαν + #if line2 != line: + # print line + # print line2 + # print + #line = line2 + #<Page[^>]*>[^< \n] + + # Ignore <Subsc..> + line = re.sub(r'<Subsc.*?>', '', line) + + # If the the line contains a Title, then it is the beginning of the next + # book, so push the next raw verse on to reset the buffer + if line.find('<Title') != -1: + rawVerses[i].append({ + 'meta':None, + 'data':line + }) + continue + + assert(len(rawVerses[i])) + + # If this line is a verse marker, save the info and go to the next line + verseMarkerMatch = reVerseMarker.match(line) + if(verseMarkerMatch): + # If the verse meta hasn't been set, then we're at the very beginning + # of a book, and so we shouldn't push on an extra raw verse, just + # save the verse meta + if not rawVerses[i][-1]['meta']: + rawVerses[i][-1]['meta'] = verseMarkerMatch.groupdict() + #print ' - ' + verseMarkerMatch.group('book') + # If we already started into a book, then this verse encountered + # means that we need to clear the buffer and start a new one + else: + # If the previous verse was empty, then eliminate it + if not rawVerses[i][-1]['data']: + rawVerses[i].pop() + + rawVerses[i].append({ + 'meta':verseMarkerMatch.groupdict(), + 'data':'' + }) + continue + + + #Append a space to the previous verse if this verse doesn't begin with + #if line and len(rawVerses[i]) > 1 and rawVerses[i][-1]['data'] and not re.match(r'^(<(PB|SB)>|\s)', line): + # print line + # rawVerses[i][-1]['data'] += ' ' + #if len(rawVerses[i]) > 1 and not rawVerses[i][-2]['data'].endswith(" "): + # rawVerses[i][-2]['data'] += " " + + # Append data to the opened verse buffer + if line and rawVerses[i][-1]['data'] and not rawVerses[i][-1]['data'].startswith('[D ') and not re.match(ur'^(<.+?>)+$', rawVerses[i][-1]['data']) and not re.match(ur'^(<.+?>)+$', line): + rawVerses[i][-1]['data'] += "\n" + rawVerses[i][-1]['data'] += line + + if files[0].closed and files[1].closed: + break + +# When all is said and done, the two verse counts should be the same +assert(len(rawVerses[0]) == len(rawVerses[1])) + + + + +# Add-in additional whitespace to ends of verses if the following verse is <del>in same book</del> +# does not begin with <SB>, <PB>, or whitespace +for rvv in rawVerses: + for i in range(0, len(rvv)-1): + if i+1 >= len(rvv): + break + if rvv[i]['data'].startswith('[D ') and not re.match(ur'^(\s|<PB>|<SB>)', rvv[i+1]['data']): + rvv[i]['data'] = re.sub(ur'(?<=\S)(?=\]\s*\[Steph)', ' ', rvv[i]['data']) + rvv[i]['data'] = re.sub(ur'(?<=\S)(?=\](?:<.+?>)?$)', ' ', rvv[i]['data']) + elif not re.match(ur'^(\s|<PB>|<SB>)', rvv[i+1]['data']) and not re.search(ur"\s$", rvv[i]['data']): + rvv[i]['data'] += ' ' + + + +####### Process Verse Contents ##################################################################################################### + + + +# The meta-data included in the transcription are all within angular brackets < >, +# except for the verse numbering, which is always preceded by $$$ and follows a +# fixed format 10 throughout. Included are page <Page = xxx>, Title <Title = ...>, +# Subscription <Subsc = ...>, Section break <SB>, and Paragraph break <PB>. + +_punctuation = re.escape(ur".·,;:!?()[]") +reToken = re.compile( + ur""" + < + (?P<metaName> SB | PB | Page | Title ) + (\s*=\s* + (?P<metaValue>.*?) + \s*)? + > + | + (?P<punctuation> [%s] ) + | + (?P<word> [^<\s%s]+ ) + | + (?P<whitespace> \s+ ) + """ % (_punctuation, _punctuation), + re.VERBOSE | re.UNICODE +) + +works = [workTNT1, workTNT2] +variantGroups = [ + varGroupTNT1, + varGroupTNT1_D, + varGroupTNT1_Steph, + varGroupTNT2, + varGroupTNT2_D, + varGroupTNT2_Steph +] + + +class PlaceholderToken(dict): + """ + Contains a regular expression match for a work; used for collating two + works' variants and merging them together before insertion into model. + + We should use Django 1.1 Proxy here + """ + + def __init__(self, **args): + for key in args: + self[key] = args[key] + + def __setattr__(self, key, val): + self[key] = val + + def __getattr__(self, key): + return self[key] + + def establish(self): + """ + This can take the values and turn this into a real token... and then + also create the many-to-many relationships. Return the new token? + """ + + token = Token( + data = self.data, + type = self.type, + position = self.position, + certainty = None, #self.certainty; handled by VariantGroupToken + work = workTNT1 + ) + #for key in self: + # if key not in ('variant_group', 'certainty'): + # token[key] = self[key] + token.save() + + vgt = VariantGroupToken( + token = token, + variant_group = self.variant_group, + certainty = self.certainty + ) + vgt.save() + return token + + def __hash__(self): + return hash(unicode(self)) + + def __eq__(self, other): + return unicode(self) == unicode(other) + + #def __str__(self): + # return unicode(self) + def __unicode__(self): + #return ("[" * self['certainty']) + self['data'] + ("]" * self['certainty']) + return import_helpers.normalize_token(self['data']) + + +def verseTokens(i): #we could pass in rawVerses[i] here + """ + Fetch the next token in the verse. + """ + + global rawVerses, works, variantGroups + + previousVerseMeta = {'book':'', 'chapter':'', 'verse':''} + bookCount = 0 + chapterCount = 0 + verseCount = 0 + openBracketsCount = 0 + variantsOpenBracketCounts = [0, 0] # 0:D, 1:Steph + tokenPosition = 0 + + for verse in rawVerses[i]: + #Mat.27.11 + #Acts.24.18 + # + if not TNT_TO_OSIS_BOOK_CODES[verse['meta']['book']] in OSIS_BIBLE_BOOK_CODES: + continue + #if verse['meta']['chapter'] != '1': + # continue + #if verse['meta']['verse'] != '10': + # continue + #if verse['meta']['book'] != 'John' or (verse['meta']['chapter'] != '8' ): #and verse['meta']['chapter'] != '7' + # continue + #if verse['meta']['book'] != '1John' or verse['meta']['chapter'] != '4': + # continue + #if verse['meta']['book'] == 'Acts' and verse['meta']['chapter'] == '24' and verse['meta']['verse'] == '18': + # okToStart = True + #if not okToStart: + # continue + #if int(verse['meta']['verse']) not in range(18, 20): + # break #stop iteration + #if not(verse['data'].startswith('[Steph ') or verse['data'].startswith('[D ')): + # continue + #if not verse['data'].count('<Page'): + # continue + #if not verse['data'].count('[['): #if not re.search(r' \[(?!Steph)', verse['data']): + # continue + + # Construct the Book ref if it is not the same as the previous + if previousVerseMeta['book'] != verse['meta']['book']: + print verse['meta']['book'] + bookCount += 1 + bookRef = Ref( + type = Ref.BOOK, + osis_id = TNT_TO_OSIS_BOOK_CODES[verse['meta']['book']], + title = OSIS_BOOK_NAMES[TNT_TO_OSIS_BOOK_CODES[verse['meta']['book']]], + work = works[i], + position = bookCount + ) + + # Get the book title if it is provided + titleMatch = re.search(r'<Title\s+=\s*(.+?)>', verse['data']) + if titleMatch: + verse['data'] = verse['data'].replace(titleMatch.group(0), '') + bookRef.title = titleMatch.group(1) + yield bookRef + + # Construct the Chapter ref if it is not the same as the previous or if the book is different (matters for single-chapter books) + if previousVerseMeta['book'] != verse['meta']['book'] or previousVerseMeta['chapter'] != verse['meta']['chapter']: + chapterCount += 1 + chapterRef = Ref( + type = Ref.CHAPTER, + osis_id = bookRef.osis_id + '.' + verse['meta']['chapter'], + numerical_start = verse['meta']['chapter'], + work = works[i], + position = chapterCount + ) + print chapterRef.osis_id + yield chapterRef + + # Construct the Verse ref if it is not the same as the previous (note there are no single-verse books) + if previousVerseMeta['verse'] != verse['meta']['verse']: + verseCount += 1 + verseRef = Ref( + type = Ref.VERSE, + osis_id = chapterRef.osis_id + '.' + verse['meta']['verse'], + numerical_start = verse['meta']['verse'], + work = works[i], + position = verseCount + ) + yield verseRef + previousVerseMeta = verse['meta'] + + # If the verse is Stephanus or Codex D, do a pre-merge ####################################################### + if verse['data'].startswith('[Steph ') or verse['data'].startswith('[D '): + # Here we have to do merge Steph and D and place into TokenContainers + + myVariantGroups = [variantGroups[i*3+1], variantGroups[i*3+2]] # 0:D, 1:Steph + tokens = [[], []] # 0:D, 1:Steph + + #[D και επορευθησαν ἑκαστος εις τον οικον αυτου.] [Steph καὶ ἐπορεύθησαν ἕκαστος εἰς τὸν οἶκον αὐτοῦ.] + varMatch = re.match(ur'\[D\s*(?P<D>.+)\]\s*\[Steph\s*(?P<Steph>.+)\]\s*(?P<extra><\w.+?>)?\s*$', verse['data'], re.UNICODE | re.DOTALL) + if not varMatch: + raise Exception("Unable to parse variant verse set (D & Steph)") + varVerses = [varMatch.group('D'), varMatch.group('Steph')] + if varMatch.group('extra'): + varVerses[1] += varMatch.group('extra') + + # Now we parse the tokens from Steph and D and place into the tokens array to merge afterward + for varIndex in (0,1): # 0:D, 1:Steph + pos = 0 + verseData = varVerses[varIndex] + + while pos < len(verseData): + tokenMatch = reToken.match(verseData, pos) + if not tokenMatch: + raise Exception("Unable to parse at position " + str(pos) + ": " + verseData) + + # Process whitespace + if tokenMatch.group('whitespace'): + tokens[varIndex].append(PlaceholderToken( + data = tokenMatch.group('whitespace'), + type = Token.WHITESPACE, + variant_group = myVariantGroups[varIndex], + certainty = variantsOpenBracketCounts[varIndex] + )) + + + # Insert word + elif tokenMatch.group('word'): + tokens[varIndex].append(PlaceholderToken( + data = tokenMatch.group('word'), + #work = works[i], + type = Token.WORD, + variant_group = myVariantGroups[varIndex], + certainty = variantsOpenBracketCounts[varIndex] + )) + + # Insert punctuation + elif tokenMatch.group('punctuation'): + if tokenMatch.group('punctuation') == '[': + variantsOpenBracketCounts[varIndex] += 1 + elif tokenMatch.group('punctuation') == ']': + variantsOpenBracketCounts[varIndex] -= 1 + else: + tokens[varIndex].append(PlaceholderToken( + data = tokenMatch.group('punctuation'), + #work = works[i], + type = Token.PUNCTUATION, + variant_group = myVariantGroups[varIndex], + certainty = variantsOpenBracketCounts[varIndex] + )) + + elif tokenMatch.group('metaName'): + # Insert page ref + if tokenMatch.group('metaName') == 'Page': + #tokens[varIndex].append(PlaceholderToken( + # data = u' PP ', + # type = Token.WHITESPACE, + # variant_group = myVariantGroups[varIndex], + # certainty = variantsOpenBracketCounts[varIndex] + #)) + + #raise Exception("CANNOT INSERT PAGE: " + tokenMatch.group('metaValue')) + tokens[varIndex].append(Ref( + type = Ref.PAGE, + position = tokenMatch.group('metaValue'), + numerical_start = tokenMatch.group('metaValue'), + work = works[i] + )) + + # Insert section + elif tokenMatch.group('metaName') == 'SB': + tokens[varIndex].append(PlaceholderToken( + data = u"§", + #work = works[i], + type = Token.PUNCTUATION, + variant_group = myVariantGroups[varIndex], + certainty = variantsOpenBracketCounts[varIndex] + )) + + # Insert paragraph + elif tokenMatch.group('metaName') == 'PB': + tokens[varIndex].append(PlaceholderToken( + data = u"¶", + #work = works[i], + type = Token.PUNCTUATION, + variant_group = myVariantGroups[varIndex], + certainty = variantsOpenBracketCounts[varIndex] + )) + + pos = tokenMatch.end() + + # Now merge tokens[0] with tokens[1], and the result will be yielded back + # 'replace' a[i1:i2] should be replaced by b[j1:j2]. + # 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. + # 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. + # 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). + # However, we need to not set variant_group to None if the certainty is not the same!!! + diffedTokenMatches = difflib.SequenceMatcher(None, tokens[0], tokens[1]) + for opcode in diffedTokenMatches.get_opcodes(): + if(opcode[0] == 'equal'): + token1indicies = range(opcode[1], opcode[2]) + token2indicies = range(opcode[3], opcode[4]) + + while(len(token1indicies)): + token1index = token1indicies.pop(0) + token2index = token2indicies.pop(0) + + assert(type(tokens[0][token1index]) == type(tokens[1][token2index])) + + # Set the position in both var1 and var2 to be the same + if isinstance(tokens[0][token1index], PlaceholderToken): + tokens[0][token1index].position = tokenPosition + tokens[1][token2index].position = tokenPosition + tokenPosition += 1 + + # (Identical tokens are detected and consolidated later) + yield tokens[0][token1index] + yield tokens[1][token2index] + + elif(opcode[0] == 'delete'): + for token1index in range(opcode[1], opcode[2]): + if isinstance(tokens[0][token1index], PlaceholderToken): + tokens[0][token1index].position = tokenPosition + tokenPosition += 1 + yield tokens[0][token1index] + + elif(opcode[0] == 'insert'): + for token2index in range(opcode[3], opcode[4]): + if isinstance(tokens[1][token2index], PlaceholderToken): + tokens[1][token2index].position = tokenPosition + tokenPosition += 1 + yield tokens[1][token2index] + + elif(opcode[0] == 'replace'): + for token1index in range(opcode[1], opcode[2]): + if isinstance(tokens[0][token1index], PlaceholderToken): + tokens[0][token1index].position = tokenPosition + tokenPosition += 1 + yield tokens[0][token1index] + for token2index in range(opcode[3], opcode[4]): + if isinstance(tokens[1][token2index], PlaceholderToken): + tokens[1][token2index].position = tokenPosition + tokenPosition += 1 + yield tokens[1][token2index] + + + + # Simply gather tokens tokens (in tokenContainers) for merging after this loop is complete ######################### + else: + + # When do we insert the refs? Best to do after the tokens have been inserted + # Instead of storing the tokenMatch in the tokenContainer, we could store the + # the actual Token objects + pos = 0 + while pos < len(verse['data']): + tokenMatch = reToken.match(verse['data'], pos) + if not tokenMatch: + raise Exception("Unable to parse at position " + str(pos) + ": " + verse['data']) + + # Process whitespace + if tokenMatch.group('whitespace'): + #Note: We should normalize this a bit. If a linebreak appears, then just insert "\n"; otherwise insert " " + #data = u" " + #if tokenMatch.group('whitespace').find("\n") != None: + # data = u"\n"; + + yield PlaceholderToken( + data = tokenMatch.group('whitespace'), + work = works[i], + type = Token.WHITESPACE, + variant_group = variantGroups[i*3], + certainty = openBracketsCount, + position = tokenPosition + ) + tokenPosition += 1 + + # Insert word + elif tokenMatch.group('word'): + yield PlaceholderToken( + data = tokenMatch.group('word'), + work = works[i], + type = Token.WORD, + variant_group = variantGroups[i*3], + certainty = openBracketsCount, + position = tokenPosition + ) + tokenPosition += 1 + + # Insert punctuation + elif tokenMatch.group('punctuation'): + if tokenMatch.group('punctuation') == '[': + openBracketsCount += 1 + elif tokenMatch.group('punctuation') == ']': + openBracketsCount -= 1 + else: + yield PlaceholderToken( + data = tokenMatch.group('punctuation'), + work = works[i], + type = Token.PUNCTUATION, + variant_group = variantGroups[i*3], + certainty = openBracketsCount, + position = tokenPosition + ) + tokenPosition += 1 + + elif tokenMatch.group('metaName'): + # Insert page ref + if tokenMatch.group('metaName') == 'Page': + + #yield PlaceholderToken( + # data = u' PP2 ', + # work = works[i], + # type = Token.WHITESPACE, + # variant_group = variantGroups[i*3], + # certainty = openBracketsCount, + # position = tokenPosition + #) + #tokenPosition += 1 + + yield Ref( + type = Ref.PAGE, + position = tokenMatch.group('metaValue'), + numerical_start = tokenMatch.group('metaValue'), + work = works[i] + ) + + # Insert section ref + elif tokenMatch.group('metaName') == 'SB': + yield PlaceholderToken( + data = u"§", + work = works[i], + type = Token.PUNCTUATION, + variant_group = variantGroups[i*3], + certainty = openBracketsCount, + position = tokenPosition + ) + tokenPosition += 1 + + # Insert paragraph ref + elif tokenMatch.group('metaName') == 'PB': + yield PlaceholderToken( + data = u"¶", + work = works[i], + type = Token.PUNCTUATION, + variant_group = variantGroups[i*3], + certainty = openBracketsCount, + position = tokenPosition + ) + tokenPosition += 1 + + pos = tokenMatch.end() + + + +# Various variables for bookkeeping +pageRefs = [[], []] +bookRefs = [[], []] +chapterRefs = [[], []] +verseRefs = [[], []] + + +def insertRef(i, ref): + if ref.type == Ref.BOOK: + bookRefs[i].append(ref) + + elif ref.type == Ref.CHAPTER: + chapterRefs[i].append(ref) + + elif ref.type == Ref.VERSE: + verseRefs[i].append(ref) + + elif ref.type == Ref.PAGE: + pageRefs[i].append(ref) + + #elif ref.type == Ref.SECTION: + # ref.position = len(sectionRefs) + # sectionRefs.append(ref) + + #elif ref.type == Ref.PARAGRAPH: + # ref.position = len(paragraphRefs) + # paragraphRefs.append(ref) + + +finalTokenPosition = 0 +tokens = [] +previousPlaceholderTokens = [] + +def insertToken(i, placeholderToken): + """ + Look behind at the previously inserted tokens to see if any of them + have the exact same tokenPosition as this token.position; if so, then + do not insert a new instance of this token, but rather associate a new + TokenVariantGroup instance to the previously-matched token + """ + global finalTokenPosition, tokens, bookRefs, chapterRefs, verseRefs, pageRefs + normalizedMatchedPreviousToken = None + + #If placeholderToken.position is different than previous token, then increment + if len(previousPlaceholderTokens) and previousPlaceholderTokens[-1].position != placeholderToken.position: + finalTokenPosition += 1 + previousPlaceholderTokens.append(placeholderToken) + + for previousToken in reversed(tokens): + # Tokens that have the exact same data or same normalized data, all have same position + if previousToken.position != finalTokenPosition: + break + # If the previous token is exactly the same as this token, then simply add the variantGroup to the existing token + if (placeholderToken.data) == (previousToken.data): + vgt = VariantGroupToken( + token = previousToken, + variant_group = placeholderToken.variant_group, + certainty = placeholderToken.certainty + ) + vgt.save() + updateRefs(i) + return + # If a previous token has the same normalized data as this token, + elif (import_helpers.normalize_token(placeholderToken.data)) == (import_helpers.normalize_token(previousToken.data)): + normalizedMatchedPreviousToken = previousToken + else: + print "Position is same (%s) but data is different \"%s\" != \"%s\"!" % (finalTokenPosition, import_helpers.normalize_token(placeholderToken.data), import_helpers.normalize_token(previousToken.data)) + raise Exception("Position is same (%s) but data is different \"%s\" != \"%s\"!" % (finalTokenPosition, import_helpers.normalize_token(placeholderToken.data), import_helpers.normalize_token(previousToken.data))) + + # Now take the placeholderToken and convert it into a real token and insert it into the database + #placeholderToken.certainty = None #Handled by variantGroupToken + placeholderToken.position = finalTokenPosition + token = placeholderToken.establish() + tokens.append(token) + updateRefs(i) + + +def updateRefs(*ii): + "Here we need to associate the previously inserted Refs with this token, and then save them" + global bookRefs, chapterRefs, verseRefs, pageRefs, tokens + + for i in ii: + for refsGroup in (bookRefs[i], chapterRefs[i], verseRefs[i], pageRefs[i]): + if not len(refsGroup): + continue + lastRef = refsGroup[-1] + + # If the refClass has not been saved, then the start_token hasn't been set + if not lastRef.id: + lastRef.start_token = tokens[-1] + lastRef.save() + + # Set the end_token to the last token parsed + lastRef.end_token = tokens[-1] + + # Set the parent of chapters and verses + if not lastRef.parent: + if lastRef.type == Ref.CHAPTER: + lastRef.parent = bookRefs[i][-1] + if lastRef.type == Ref.VERSE: + lastRef.parent = chapterRefs[i][-1] + + +# Grab tokens from TNT1 and TNT2 +placeholderTokens = [[], []] +for token in verseTokens(0): + placeholderTokens[0].append(token) +for token in verseTokens(1): + placeholderTokens[1].append(token) + + +# Now merge placeholderTokens[0] and placeholderTokens[1]; remember, the differences are going to +# be in punctuation and in accentation; we need to ensire that placeholderTokens with +# differing accentation are stored in the same position + +# Now merge placeholderTokens[0] with placeholderTokens[1], and the result will be yielded back +# 'replace' a[i1:i2] should be replaced by b[j1:j2]. +# 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. +# 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. +# 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). +# However, we need to not set variant_group to None if the certainty is not the same!!! +print "Merging tokens..." +tokenPosition = 0 +previousMergedPlaceholderPositions = [[], []] +diffedTokenMatches = difflib.SequenceMatcher(None, placeholderTokens[0], placeholderTokens[1]) +for opcode in diffedTokenMatches.get_opcodes(): + if(opcode[0] == 'equal'): + token1indicies = range(opcode[1], opcode[2]) + token2indicies = range(opcode[3], opcode[4]) + + while(len(token1indicies)): + token1index = token1indicies.pop(0) + token2index = token2indicies.pop(0) + + # Set the position in both var1 and var2 to be the same + if isinstance(placeholderTokens[0][token1index], Ref): + insertRef(0, placeholderTokens[0][token1index]) + insertRef(1, placeholderTokens[1][token2index]) + # Otherwise, insert both placeholderTokens but at the same position to indicate that they are alternates of the same + else: + assert(import_helpers.normalize_token(placeholderTokens[0][token1index].data) == import_helpers.normalize_token(placeholderTokens[1][token2index].data)) + + # Only increment the token position if these equal tokens are a different position than the previously seen token + if len(previousMergedPlaceholderPositions[0]) and previousMergedPlaceholderPositions[0][-1] != placeholderTokens[0][token1index].position: + tokenPosition += 1 + elif len(previousMergedPlaceholderPositions[1]) and previousMergedPlaceholderPositions[1][-1] != placeholderTokens[1][token2index].position: + tokenPosition += 1 + + previousMergedPlaceholderPositions[0].append(placeholderTokens[0][token1index].position) + previousMergedPlaceholderPositions[1].append(placeholderTokens[1][token2index].position) + + placeholderTokens[0][token1index].position = tokenPosition + placeholderTokens[1][token2index].position = tokenPosition + + insertToken(0, placeholderTokens[0][token1index]) + insertToken(1, placeholderTokens[1][token2index]) + + elif(opcode[0] == 'delete'): + for token1index in range(opcode[1], opcode[2]): + if isinstance(placeholderTokens[0][token1index], Ref): + insertRef(0, placeholderTokens[0][token1index]) + else: + if len(previousMergedPlaceholderPositions[0]) and previousMergedPlaceholderPositions[0][-1] != placeholderTokens[0][token1index].position: + tokenPosition += 1 + previousMergedPlaceholderPositions[0].append(placeholderTokens[0][token1index].position) + placeholderTokens[0][token1index].position = tokenPosition + insertToken(0, placeholderTokens[0][token1index]) + + elif(opcode[0] == 'insert'): + for token2index in range(opcode[3], opcode[4]): + if isinstance(placeholderTokens[1][token2index], Ref): + insertRef(1, placeholderTokens[1][token2index]) + else: + if len(previousMergedPlaceholderPositions[1]) and previousMergedPlaceholderPositions[1][-1] != placeholderTokens[1][token2index].position: + tokenPosition += 1 + previousMergedPlaceholderPositions[1].append(placeholderTokens[1][token2index].position) + placeholderTokens[1][token2index].position = tokenPosition + insertToken(1, placeholderTokens[1][token2index]) + + elif(opcode[0] == 'replace'): + for token1index in range(opcode[1], opcode[2]): + if isinstance(placeholderTokens[0][token1index], Ref): + insertRef(0, placeholderTokens[0][token1index]) + else: + if len(previousMergedPlaceholderPositions[0]) and previousMergedPlaceholderPositions[0][-1] != placeholderTokens[0][token1index].position: + tokenPosition += 1 + previousMergedPlaceholderPositions[0].append(placeholderTokens[0][token1index].position) + placeholderTokens[0][token1index].position = tokenPosition + insertToken(0, placeholderTokens[0][token1index]) + for token2index in range(opcode[3], opcode[4]): + if isinstance(placeholderTokens[1][token2index], Ref): + insertRef(1, placeholderTokens[1][token2index]) + else: + if len(previousMergedPlaceholderPositions[1]) and previousMergedPlaceholderPositions[1][-1] != placeholderTokens[1][token2index].position: + tokenPosition += 1 + previousMergedPlaceholderPositions[1].append(placeholderTokens[1][token2index].position) + placeholderTokens[1][token2index].position = tokenPosition + insertToken(1, placeholderTokens[1][token2index]) + + +# Save all refs now that start_tokens and end_tokens have all been set +for i in (0,1): + for refsGroup in (bookRefs[i], chapterRefs[i], verseRefs[i], pageRefs[i]): + for ref in refsGroup: + ref.save() + diff --git a/data/manuscripts/Tischendorf-2.5.py b/data/manuscripts/Tischendorf-2.5.py new file mode 100644 index 0000000..518dd3d --- /dev/null +++ b/data/manuscripts/Tischendorf-2.5.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python +# encoding: utf-8 + +msQereID = 4 +msKethivID = 12 + +import sys, os, re, unicodedata, urllib, zipfile, StringIO +from datetime import date +from django.core.management import setup_environ +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) #There's probably a better way of doing this +from openscriptures import settings +setup_environ(settings) +from openscriptures.core.models import * +from openscriptures.data import import_helpers + +# Abort if MS has already been added (or --force not supplied) +import_helpers.abort_if_imported(msQereID) + +# Download the source file +source_url = "http://files.morphgnt.org/tischendorf/Tischendorf-2.5.zip" +import_helpers.download_resource(source_url) + + +# Work for Kethiv edition (base text for qere) +import_helpers.delete_work(msKethivID) +msKethivWork = Work( + id = msKethivID, + title = "Tischendorf 8th ed. v2.5 (Kethiv)", + language = Language('grc'), + type = 'Bible', + osis_slug = 'Tischendorf', + publish_date = date(2009, 1, 1), + originality = 'manuscript-edition', + creator = "<a href='http://en.wikipedia.org/wiki/Constantin_von_Tischendorf' title='Constantin von Tischendorf @ Wikipedia'>Constantin von Tischendorf</a>. Based on G. Clint Yale's Tischendorf text and on Dr. Maurice A. Robinson's Public Domain Westcott-Hort text. Edited by <a href='http://www.hum.aau.dk/~ulrikp/'>Ulrik Sandborg-Petersen</a>.", + url = source_url, + license = License.objects.get(url="http://creativecommons.org/licenses/publicdomain/") +) +msKethivWork.save() + +varGroupKethiv = VariantGroup( + work = msKethivWork, + primacy = 0 +) +varGroupKethiv.save() + +# Work for Qere edition (Kethiv is base text) +import_helpers.delete_work(msQereID) +msQereWork = Work( + id = msQereID, + title = "Tischendorf 8th ed. v2.5 (Qere)", + language = Language('grc'), + type = 'Bible', + osis_slug = 'Tischendorf', + publish_date = date(2009, 1, 1), + originality = 'manuscript-edition', + creator = "<a href='http://en.wikipedia.org/wiki/Constantin_von_Tischendorf' title='Constantin von Tischendorf @ Wikipedia'>Constantin von Tischendorf</a>. Based on G. Clint Yale's Tischendorf text and on Dr. Maurice A. Robinson's Public Domain Westcott-Hort text. Edited by <a href='http://www.hum.aau.dk/~ulrikp/'>Ulrik Sandborg-Petersen</a>.", + url = source_url, + license = License.objects.get(url="http://creativecommons.org/licenses/publicdomain/") +) +msQereWork.save() + +varGroupQere = VariantGroup( + work = msQereWork, + primacy = 0 +) +varGroupQere.save() + + + + +bookFilenameLookup = { + 'Matt' : "MT.txt" , + 'Mark' : "MR.txt" , + 'Luke' : "LU.txt" , + 'John' : "JOH.txt" , + 'Acts' : "AC.txt" , + 'Rom' : "RO.txt" , + '1Cor' : "1CO.txt" , + '2Cor' : "2CO.txt" , + 'Gal' : "GA.txt" , + 'Eph' : "EPH.txt" , + 'Phil' : "PHP.txt" , + 'Col' : "COL.txt" , + '1Thess' : "1TH.txt" , + '2Thess' : "2TH.txt" , + '1Tim' : "1TI.txt" , + '2Tim' : "2TI.txt" , + 'Titus' : "TIT.txt" , + 'Phlm' : "PHM.txt" , + 'Heb' : "HEB.txt" , + 'Jas' : "JAS.txt" , + '1Pet' : "1PE.txt" , + '2Pet' : "2PE.txt" , + '1John' : "1JO.txt" , + '2John' : "2JO.txt" , + '3John' : "3JO.txt" , + 'Jude' : "JUDE.txt" , + 'Rev' : "RE.txt" , +} + +#NOTICE: We need to do the same thing with Tischendorf that we did with TNT: there is a corrected edition +# - One word per line +# - Space-separated fields (except for the last two) +# - - fields: +# 0. Book (corresponds to the filename, which is the Online Bible standard) +# 1. Chapter:Verse.word-within-verse +# 2. Pagraph break ("P") / Chapter break ("C") / No break (".") (see +# below) +# 3. The text as it is written in the printed Tischendorf (Kethiv) +# 4. The text as the editor thinks it should have been (Qere) +# 5. The morphological tag (following the Qere) +# 6. The Strong's number (following the Qere) +# 7. The lemma in two versions: +# 7.a The first version, which corresponds to The NEW Strong's +# Complete Dictionary of Bible Words. +# 7.b Followed by the string " ! " +# 7.c Then the second version, which corresponds to Friberg, Friberg +# and Miller's ANLEX. +# There may be several words in each lemma. +# +# All Strong's numbers are single numbers with 1,2,3, or 4 digits. +# +# The third column (designated "2." above) has precisely one of three +# values: +# +# - "." : No break occurs +# - "P" : A paragraph break occurs +# - "C" : A chapter break occurs +# +# Most paragraph breaks occur on a verse boundary, but not all paragraph +# breaks do. +# +# A program counting the "C"s can rely on them to count the chapters, +# i.e., even if a chapter break occurs in a verse which belongs to +# chapter X, that means that Tischendorf thought that that verse belongs +# to chapter X+1. This occurs, for example, in Revelation 12:18, where +# the chapter break occurs in chapter 12, meaning that verse 12:18 needs +# to be shown with chapter 13. + + +#puncchrs = re.escape(''.join(unichr(x) for x in range(65536) if unicodedata.category(unichr(x)) == 'Po')) +puncchrs = re.escape(ur'.·,;:!?"\'') +lineParser = re.compile(ur"""^ + (?P<book>\S+)\s+ # Book (corresponds to the filename, which is the Online Bible standard) + (?P<chapter>\d+): # Chapter + (?P<verse>\d+)\. # Verse + (?P<position>\d+)\s+ # word-within-verse + (?P<break>\S)\s+ # Pagraph break ("P") / Chapter break ("C") / No break (".") + (?P<kethivStartBracket>\[)? + (?P<kethiv>\S+?) # The text as it is written in the printed Tischendorf (Kethiv) + (?P<kethivPunc>[%s])?\s+ # Kethiv punctuation + (?P<kethivEndBracket>\])? + (?P<rawParsing> + (?P<qereStartBracket>\[)? + (?P<qere>\S+?) # The text as the editor thinks it should have been (Qere) + (?P<qerePunc> [%s])?\s+ # Qere punctuation + (?P<qereEndBracket>\])? + (?P<morph>\S+)\s+ # The morphological tag (following the Qere) + (?P<strongsNumber>\d+)\s+ # The Strong's number (following the Qere) + (?P<strongsLemma>.+?) # Lemma which corresponds to The NEW Strong's Complete Dictionary of Bible Words. (There may be several words in each lemma.) + \s+!\s+ # A " ! " separates the lemmas + (?P<anlexLemma>.+?) # Lemma which corresponds to Friberg, Friberg and Miller's ANLEX. (There may be several words in each lemma.) + ) + \s*$""" % (puncchrs, puncchrs), + re.VERBOSE +) + +works = [msKethivWork, msQereWork] +bookRefs = [[], []] +bookTokens = [[], []] +openBrackets = [0,0] +precedingTokenCount = 0 + +zip = zipfile.ZipFile(os.path.basename(source_url)) +for book_code in OSIS_BIBLE_BOOK_CODES: + print OSIS_BOOK_NAMES[book_code] + + precedingTokenCount = precedingTokenCount + len(max(bookTokens[0], bookTokens[1])) + bookTokens = [] + chapterRefs = [] + verseRefs = [] + + # Set up the book ref + bookRefKethiv = Ref( + work = msKethivWork, + type = Ref.BOOK, + osis_id = book_code, + position = len(bookRefs), + title = OSIS_BOOK_NAMES[book_code] + ) + bookRefQere = Ref( + work = msQereWork, + type = Ref.BOOK, + osis_id = book_code, + position = len(bookRefs), + title = OSIS_BOOK_NAMES[book_code] + ) + + for line in StringIO.StringIO(zip.read("Tischendorf-2.5/Unicode/" + bookFilenameLookup[book_code])): + line = unicodedata.normalize("NFC", unicode(line, 'utf-8')) + + word = lineParser.match(line) + if word is None: + print " -- Warning: Unable to parse line: " + line + continue + + # If this is a paragraph break, insert new paragraph token + if word.group('break') == 'P': + token = Token( + data = "¶", + type = Token.PUNCTUATION, + work = msQereWork, + position = precedingTokenCount + len(bookTokens) + ) + token.save() + bookTokens.append(token) #NOTE: identical for both Qere and Kethiv, so no variant group needed + + # Insert whitespace if preceding token isn't a puctuation or whitespace + elif word.group('break') == '.' and len(bookTokens) and bookTokens[-1].type not in (Token.PUNCTUATION, Token.WHITESPACE): + token = Token( + data = " ", + type = Token.WHITESPACE, + work = msQereWork, + position = precedingTokenCount + len(bookTokens) + ) + token.save() + bookTokens.append(token) #NOTE: identical for both Qere and Kethiv, so no variant group needed + + if word.group('qereStartBracket'): + openBrackets[0] += 1 + if word.group('kethivStartBracket'): + openBrackets[1] += 1 + + # Insert token + #QUESTION: If the token is identical for both kethiv and qere, what if + # don't provide variants? Is it even necessary? Will we even be + # able to query tokens that don't have a variant? + token = Token( + data = word.group('qere'), + type = Token.WORD, + work = msQereWork, + position = precedingTokenCount + len(bookTokens) + ) + token.save() + bookTokens.append(token) + + # Token Parsing + parsing = TokenParsing( + token = token, + parse = word.group('morph'), + strongs = word.group('strongsNumber'), + lemma = word.group('strongsLemma') + '; ' + word.group('anlexLemma'), + language = Language('grc'), + work = msQereWork + ) + parsing.save() + + # Insert punctuation + if(word.group('qerePunc')): + token = Token( + data = word.group('qerePunc'), + type = Token.PUNCTUATION, + work = msQereWork, + position = precedingTokenCount + len(bookTokens) + ) + token.save() + bookTokens.append(token) + + if word.group('qereEndBracket'): + openBrackets[0] -= 1 + if word.group('kethivEndBracket'): + openBrackets[1] -= 1 + + # Make this token the first in the book ref, and set the first token in the book + if len(bookTokens) == 1: + bookRef.start_token = bookTokens[0] + bookRef.save() + bookRefs.append(bookRef) + + # Set up the Chapter ref + if(not len(chapterRefs) or word.group('chapter') != chapterRefs[-1].numerical_start): + if(len(chapterRefs)): + chapterRefs[-1].end_token = bookTokens[-2] + chapterRef = Ref( + work = msQereWork, + type = Ref.CHAPTER, + osis_id = ("%s.%s" % (book_code, word.group('chapter'))), + position = len(chapterRefs), + parent = bookRef, + numerical_start = word.group('chapter'), + start_token = bookTokens[-1] + ) + chapterRef.save() + chapterRefs.append(chapterRef) + + # Set up the Verse Ref + if(not len(verseRefs) or word.group('verse') != verseRefs[-1].numerical_start): + if(len(verseRefs)): + verseRefs[-1].end_token = bookTokens[-2] + verseRef = Ref( + work = msQereWork, + type = Ref.VERSE, + osis_id = ("%s.%s" % (chapterRef.osis_id, word.group('verse'))), + position = len(verseRefs), + parent = chapterRefs[-1], + numerical_start = word.group('verse'), + start_token = token + ) + verseRef.save() + verseRefs.append(verseRef) + + #Save all books, chapterRefs, and verseRefs + bookRef.end_token = bookTokens[-1] + bookRef.save() + chapterRefs[-1].end_token = bookTokens[-1] + for chapterRef in chapterRefs: + chapterRef.save() + verseRefs[-1].end_token = bookTokens[-1] + for verseRef in verseRefs: + verseRef.save() + + diff --git a/data/manuscripts/greek_WH_UBS4_parsed.py b/data/manuscripts/greek_WH_UBS4_parsed.py new file mode 100644 index 0000000..7826593 --- /dev/null +++ b/data/manuscripts/greek_WH_UBS4_parsed.py @@ -0,0 +1,409 @@ +#!/usr/bin/env python +# encoding: utf-8 + +msID = 2 +varMsID = 3 + +import sys, os, re, unicodedata, difflib, zipfile, StringIO +from datetime import date +from django.core.management import setup_environ +from django.utils.encoding import smart_str, smart_unicode +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) #There's probably a better way of doing this +from openscriptures import settings +setup_environ(settings) +from openscriptures.data.unbound_bible import UNBOUND_CODE_TO_OSIS_CODE # Why does this have to be explicit? +from openscriptures.data import import_helpers +from openscriptures.core.models import * + +# Abort if MS has already been added (or --force not supplied) +import_helpers.abort_if_imported(msID) + +# Download the source file +source_url = "http://www.unboundbible.org/downloads/bibles/greek_WH_UBS4_parsed.zip" +import_helpers.download_resource(source_url) + +# Delete existing works and their contents +import_helpers.delete_work(msID, varMsID) + +msWork = Work( + id = msID, + title = "Westcott/Hort", + abbreviation = "W/H", + language = Language('grc'), + type = 'Bible', + osis_slug = 'WH', + publish_date = date(1881, 1, 1), + originality = 'manuscript-edition', + creator = "By <a href='http://en.wikipedia.org/wiki/Brooke_Foss_Westcott' title='Brooke Foss Westcott @ Wikipedia'>Brooke Foss Westcott</a> and <a href='http://en.wikipedia.org/wiki/Fenton_John_Anthony_Hort' title='Fenton John Anthony Hort @ Wikipedia'>Fenton John Anthony Hort</a>.", + url = source_url, + #variant_number = 1, + license = License.objects.filter(url="http://creativecommons.org/licenses/publicdomain/")[0] +) +msWork.save() + +varGroup1 = VariantGroup( + work = msWork, + primacy = 0 +) +varGroup1.save() + +# Now we need to create additional works for each set of variants that this work contains +# Diff/variant works will have tokens that have positions that are the same as those in the base work? The base work's tokens will have positions that have gaps? +# When processing a line with enclosed variants, it will be important to construct the verse for VAR1, VAR2, etc... and then merge these together. +#variantWork = Work( +# id = varMsID, +# title = "UBS4 Variants", +# abbreviation = "UBS4-var", +# language = Language('grc'), +# type = 'Bible', +# osis_slug = 'UBS4-var', +# publish_date = date(1993, 1, 1), +# originality = 'manuscript-edition', +# creator = "By <a href='http://en.wikipedia.org/wiki/Eberhard_Nestle' title='Eberhard Nestle @ Wikipedia'>Eberhard Nestle</a>, <a href='http://en.wikipedia.org/wiki/Erwin_Nestle' title='Erwin Nestle @ Wikipedia'>Erwin Nestle</a>, <a href='http://en.wikipedia.org/wiki/Kurt_Aland' title='Kurt Aland @ Wikipedia'>Kurt Aland</a>, <a href='http://www.biblesociety.org/'>United Bible Societies</a> et al", +# url = source_url, +# base = msWork, +# #variant_number = 2, +# license = License.objects.get(url="http://en.wikipedia.org/wiki/Fair_use") +#) +#variantWork.save() + +varGroup2 = VariantGroup( + work = msWork, + primacy = 1, + title = "UBS4 Variants", + license = License.objects.get(url="http://en.wikipedia.org/wiki/Fair_use") +) +varGroup2.save() + +# The followig regular epression identifies the parts of the following line: +# 40N 1 1 10 Βίβλος G976 N-NSF γενέσεως G1078 N-GSF Ἰησοῦ G2424 N-GSM χριστοῦ G5547 N-GSM , υἱοῦ G5207 N-GSM Δαυίδ G1138 N-PRI , υἱοῦ G5207 N-GSM Ἀβραάμ G11 N-PRI . +lineParser = re.compile(ur"""^ + (?P<book>\d+\w+)\t+ # Unbound Bible Code + (?P<chapter>\d+)\t+ # Chapter + (?P<verse>\d+)\t+ # Verse + \d+\t+ # Ignore orderby column + (?P<data>.*?) + \s*$""", + re.VERBOSE +) + +# Regular expression to parse each individual word on a line (the data group from above) +tokenParser = re.compile(ur""" + \[*(?P<word>ινα\s+τι|\S+?)\]*\s+ + + (?P<rawParsing> + G?\d+ + (?: \s+G?\d+ | \s+[A-Z0-9\-:]+ | \] )+ + ) + + #(?P<strongs1>G?\d+)\]*\s+ + #(?: + # G?(?P<strongs2>\d+\]*)\s+ + #)? + #(?P<parsing>[A-Z0-9\-]+)\]* + #(?P<extra> + # (?: \s+G?\d+ | \s+[A-Z0-9\-:]+ | \] )+ + #)? + (?:\s+|$) + """, + re.VERBOSE | re.UNICODE) + +# We need to deal with single variant brackets and double variant brackets; actually, what we need to do is pre-process the entire file and fix the variant brackets +#reMatchVariantString = re.compile(ur"\[\s*([^\]]+\s[^\]]+?)\s*\]") #re.compile(ur"(\[(?!\s)\b\p{Greek}+.+?\p{Greek}\b(?<!\s)\])") + +# Compile the regular expressions that are used to isolate the variants for each work +reFilterVar1 = re.compile(ur"\s* ( {VAR[^1]:.+?} | {VAR1: | } )""", re.VERBOSE) +reFilterVar2 = re.compile(ur"\s* ( {VAR[^2]:.+?} | {VAR2: | } )""", re.VERBOSE) +reHasVariant = re.compile(ur'{VAR') +reHasBracket = re.compile(ur'\[|\]') + +bookRefs = [] +chapterRefs = [] +verseRefs = [] +tokens = [] +previousTokens = [] + + +class TokenContainer: + "Contains a regular expression match for a work; used for collating two works' variants and merging them together before insertion into model" + def __init__(self, match, variant_group = None, position = None, open_brackets = 0): + self.match = match + self.variant_group = variant_group + self.position = position + self.open_brackets = open_brackets + + #def __unicode__(self): + # s = ('[' * self.open_brackets) + self.match['word'] + (']' * self.open_brackets) + # if self.variant_group: + # s += '-' + str(self.variant_group.id) + # return s + + def __hash__(self): + return hash(self.match['word']) + + def __eq__(self, other): + return self.match['word'] == other.match['word'] + +var1OpenBrackets = 0 +var2OpenBrackets = 0 + +tokenPosition = 0 + +zip = zipfile.ZipFile(os.path.basename(source_url)) +for verseLine in StringIO.StringIO(zip.read("greek_WH_UBS4_parsed_utf8.txt")): + if(verseLine.startswith('#')): + continue + verseLine = unicodedata.normalize("NFC", smart_unicode(verseLine)) + verseInfo = lineParser.match(verseLine) + if(not verseInfo): + raise Exception("Parse error on line: " + verseLine) + if(not verseInfo.group('data') or UNBOUND_CODE_TO_OSIS_CODE[verseInfo.group('book')] not in OSIS_BIBLE_BOOK_CODES): + continue + meta = verseInfo.groupdict() + + tokenContainers = [] + verseTokens = [] + + # Parse words for both variants, or if there are open brackets or if this verse has brackets, then we need to do some special processing + # Regarding two editions having identical variants but differing degrees of assurance: we will have to not insert them as Token(variant_group=None) but rather + # as two tokens at the same position with different variant_groups and different certainties: + # Token(variant_group=1, position=X, certainty=0) + # Token(variant_group=2, position=X, certainty=1) + if((var1OpenBrackets or var2OpenBrackets) or reHasVariant.search(meta['data']) or reHasBracket.search(meta['data'])): + + # Get the tokens from the first variant + verseVar1 = reFilterVar1.sub('', meta['data']).strip() + verseTokensVar1 = [] + pos = 0 + while(pos < len(verseVar1)): + tokenMatch = tokenParser.match(verseVar1, pos) + if(not tokenMatch): + print "at " + str(pos) + ": " + verseVar1 + raise Exception("Parse error") + token = TokenContainer(tokenMatch.groupdict(), varGroup1) + + # Determine if this token is within brackets + if(re.search(r'\[\[', verseVar1[tokenMatch.start() : tokenMatch.end()])): + var1OpenBrackets = 2 + elif(re.search(r'\[', verseVar1[tokenMatch.start() : tokenMatch.end()])): + var1OpenBrackets = 1 + token.open_brackets = var1OpenBrackets + + # Determine if this token is the last one in brackets + if(re.search(r'\]', verseVar1[tokenMatch.start() : tokenMatch.end()])): + var1OpenBrackets = 0 + + verseTokensVar1.append(token) + pos = tokenMatch.end() + + # Get the tokens from the second variant + verseVar2 = reFilterVar2.sub('', meta['data']).strip() + verseTokensVar2 = [] + pos = 0 + while(pos < len(verseVar2)): + tokenMatch = tokenParser.match(verseVar2, pos) + if(not tokenMatch): + print "at " + str(pos) + ": " + verseVar2 + raise Exception("Parse error") + token = TokenContainer(tokenMatch.groupdict(), varGroup2) + + # Determine if this token is within brackets + if(re.search(r'\[\[', verseVar2[tokenMatch.start() : tokenMatch.end()])): + var2OpenBrackets = 2 + elif(re.search(r'\[', verseVar2[tokenMatch.start() : tokenMatch.end()])): + var2OpenBrackets = 1 + token.open_brackets = var2OpenBrackets + + # Determine if this token is the last one in brackets + if(re.search(r'\]', verseVar2[tokenMatch.start() : tokenMatch.end()])): + var2OpenBrackets = 0 + + verseTokensVar2.append(token) + pos = tokenMatch.end() + + # Now merge verseTokensVar1 and verseTokensVar2 into verseTokens, and then set each token's position according to where it was inserted + # 'replace' a[i1:i2] should be replaced by b[j1:j2]. + # 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. + # 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. + # 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). + # However, we need to not set variant_group to None if the certainty is not the same!!! + diffedTokenMatches = difflib.SequenceMatcher(None, verseTokensVar1, verseTokensVar2) + for opcode in diffedTokenMatches.get_opcodes(): + if(opcode[0] == 'equal'): + var1indicies = range(opcode[1], opcode[2]) + var2indicies = range(opcode[3], opcode[4]) + + while(len(var1indicies)): + i = var1indicies.pop(0) + j = var2indicies.pop(0) + + # Set the position in both var1 and var2 to be the same + verseTokensVar1[i].position = tokenPosition + verseTokensVar2[j].position = tokenPosition + #print verseTokensVar1[i].match['word'] + " == " + verseTokensVar2[j].match['word'] + + # If the two variants are identical even in the open bracket count, then only insert one and set + # variant_group to None because there is absolutely no variance + if(verseTokensVar1[i].open_brackets == verseTokensVar2[j].open_brackets): + verseTokensVar1[i].variant_group = None + tokenContainers.append(verseTokensVar1[i]) + # The open_bracket count in the two tokens is different, so insert both but at the exact same position + else: + tokenContainers.append(verseTokensVar1[i]) + tokenContainers.append(verseTokensVar2[j]) + tokenPosition += 1 + elif(opcode[0] == 'delete'): + for i in range(opcode[1], opcode[2]): + #print "1: " + verseTokensVar1[i].match['word'] + " (delete)" + verseTokensVar1[i].position = tokenPosition + tokenPosition += 1 + tokenContainers.append(verseTokensVar1[i]) + elif(opcode[0] == 'insert'): + for i in range(opcode[3], opcode[4]): + #print "2: " + verseTokensVar2[i].match['word'] + " (insert)" + verseTokensVar2[i].position = tokenPosition + tokenPosition += 1 + tokenContainers.append(verseTokensVar2[i]) + elif(opcode[0] == 'replace'): + #print str(verseTokensVar1[opcode[1]] == verseTokensVar2[opcode[3]]) + " THATIS " + (verseTokensVar1[opcode[1]].normalized_word) + " == " + (verseTokensVar2[opcode[3]].normalized_word) + for i in range(opcode[1], opcode[2]): + #print "1: " + verseTokensVar1[i].match['word'] + " (replace)" + verseTokensVar1[i].position = tokenPosition + tokenPosition += 1 + tokenContainers.append(verseTokensVar1[i]) + for i in range(opcode[3], opcode[4]): + #print "2: " + verseTokensVar2[i].match['word'] + " (replace)" + verseTokensVar2[i].position = tokenPosition + tokenPosition += 1 + tokenContainers.append(verseTokensVar2[i]) + + # No variants and there weren't any variant brackets, so just parse them out of one verse + else: + pos = 0 + while(pos < len(meta['data'])): + tokenMatch = tokenParser.match(meta['data'], pos) + if(not tokenMatch): + print "%s %02d %02d" % (verseInfo.group('book'), int(verseInfo.group('chapter')), int(verseInfo.group('verse'))) + print "Unable to parse at position " + str(pos) + ": " + verseInfo.group('data') + raise Exception("Unable to parse at position " + str(pos) + ": " + verseInfo.group('data')) + tokenContainers.append(TokenContainer(tokenMatch.groupdict(), None, tokenPosition)) + tokenPosition += 1 + pos = tokenMatch.end() + + # Create book ref if it doesn't exist + if(not len(bookRefs) or bookRefs[-1].osis_id != UNBOUND_CODE_TO_OSIS_CODE[meta['book']]): + print UNBOUND_CODE_TO_OSIS_CODE[meta['book']] + + # Reset tokens + previousTokens = tokens + tokens = [] + + # Close book and chapter refs + if(len(previousTokens)): + bookRefs[-1].end_token = previousTokens[-1] + bookRefs[-1].save() + chapterRefs[-1].end_token = previousTokens[-1] + chapterRefs[-1].save() + chapterRefs = [] + verseRefs = [] + + # Set up the book ref + bookRef = Ref( + work = msWork, + type = Ref.BOOK, + osis_id = UNBOUND_CODE_TO_OSIS_CODE[meta['book']], + position = len(bookRefs), + title = OSIS_BOOK_NAMES[UNBOUND_CODE_TO_OSIS_CODE[meta['book']]] + ) + #bookRef.save() + #bookRefs.append(bookRef) + + # Now process the tokens like normal + verseTokens = [] + + lastTokenContainer = None + for tokenContainer in tokenContainers: + + # Only do this if the previous token is different than this token + if not lastTokenContainer or lastTokenContainer.position != tokenContainer.position or lastTokenContainer.match['word'] != tokenContainer.match['word']: + token = Token( + data = tokenContainer.match['word'], + type = Token.WORD, + work = msWork, + position = tokenContainer.position, + #variant_group = tokenContainer.variant_group, + certainty = tokenContainer.open_brackets + ) + token.save() + tokens.append(token) + verseTokens.append(token) + + # Associate the token its respective variant group if it has one + if tokenContainer.variant_group: + vgt = VariantGroupToken( + variant_group = tokenContainer.variant_group, + token = tokens[-1], + certainty = tokenContainer.open_brackets + ) + vgt.save() + + # Token Parsing + #strongs = [tokenContainer.match['strongs1']] + #if(tokenContainer.match['strongs2']): + # strongs.append(tokenContainer.match['strongs2']) + parsing = TokenParsing( + token = token, + raw = tokenContainer.match['rawParsing'], + #parse = tokenContainer.match['parsing'], + #strongs = ";".join(strongs), + language = Language('grc'), + work = msWork + ) + parsing.save() + + # Make this token the first in the book ref, and set the first token in the book + if len(tokens) == 1: + bookRef.start_token = tokens[0] + bookRef.save() + bookRefs.append(bookRef) + + # Set up the Chapter ref + if(not len(chapterRefs) or chapterRefs[-1].numerical_start != meta['chapter']): + if(len(chapterRefs)): + chapterRefs[-1].end_token = tokens[-2] + chapterRefs[-1].save() + chapterRef = Ref( + work = msWork, + type = Ref.CHAPTER, + osis_id = ("%s.%s" % (bookRefs[-1].osis_id, meta['chapter'])), + position = len(chapterRefs), + parent = bookRefs[-1], + numerical_start = meta['chapter'], + start_token = tokens[-1] + ) + chapterRef.save() + chapterRefs.append(chapterRef) + + lastTokenContainer = tokenContainer + + # Create verse ref + verseRef = Ref( + work = msWork, + type = Ref.VERSE, + osis_id = ("%s.%s.%s" % (bookRefs[-1].osis_id, meta['chapter'], meta['verse'])), + position = len(verseRefs), + parent = chapterRefs[-1], + numerical_start = meta['verse'], + start_token = verseTokens[0], + end_token = verseTokens[-1] + ) + verseRef.save() + verseRefs.append(verseRef) + +#Close out the last book and save the chapters +bookRefs[-1].end_token = tokens[-1] +bookRefs[-1].save() +chapterRefs[-1].end_token = tokens[-1] +chapterRefs[-1].save() +#for chapterRef in chapterRefs: +# chapterRef.save() \ No newline at end of file diff --git a/data/manuscripts/greek_byzantine_2000_parsed.py b/data/manuscripts/greek_byzantine_2000_parsed.py new file mode 100644 index 0000000..680662e --- /dev/null +++ b/data/manuscripts/greek_byzantine_2000_parsed.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python +# encoding: utf-8 + +msID = 5 + +import sys, os, re, unicodedata, urllib, zipfile, StringIO +from datetime import date +from django.core.management import setup_environ +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) #There's probably a better way of doing this +from openscriptures import settings +setup_environ(settings) +from openscriptures.data.unbound_bible import UNBOUND_CODE_TO_OSIS_CODE # Why does this have to be explicit? +from openscriptures.core.models import * +from openscriptures.data import import_helpers + +# Abort if MS has already been added (and --force not supplied) +import_helpers.abort_if_imported(msID) + +# Download the source file +source_url = "http://www.unboundbible.org/downloads/bibles/greek_byzantine_2000_parsed.zip" +import_helpers.download_resource(source_url) + +import_helpers.delete_work(msID) +msWork = Work( + id = msID, + title = "Byzantine/Majority Text (2000)", + description = "Includes parsings", + abbreviation = 'Byz-2000', + language = Language('grc'), + type = 'Bible', + osis_slug = 'Byzantine', + publish_date = date(2000, 1, 1), + originality = 'manuscript-edition', + creator = "Maurice A. Robinson and William G. Pierpont.", + url = source_url, + license = License.objects.get(url="http://creativecommons.org/licenses/publicdomain/") +) +msWork.save() + +# The followig regular epression identifies the parts of the following line: +# 40N 1 1 10 Βίβλος G976 N-NSF γενέσεως G1078 N-GSF Ἰησοῦ G2424 N-GSM χριστοῦ G5547 N-GSM , υἱοῦ G5207 N-GSM Δαυίδ G1138 N-PRI , υἱοῦ G5207 N-GSM Ἀβραάμ G11 N-PRI . +lineParser = re.compile(ur"""^ + (?P<book>\d+\w+)\t+ # Unbound Bible Code + (?P<chapter>\d+)\t+ # Chapter + (?P<verse>\d+)\t+ # Verse + \d+\t+ # Ignore orderby column + (?P<data>.*?) + \s*$""", + re.VERBOSE +) + +# Regular expression to parse each individual word on a line (the data group from above) +tokenParser = re.compile(ur""" + (?P<word>\S+)\s+ + (?P<rawParsing> + G?\d+ + (?: \s+G?\d+ | \s+[A-Z0-9\-:]+ )+ + ) + (?:\s+|$) + """, + re.VERBOSE | re.UNICODE) + +bookRefs = [] +chapterRefs = [] +verseRefs = [] +tokens = [] +previousTokens = [] +tokenPosition = 0 + +zip = zipfile.ZipFile(os.path.basename(source_url)) +for verseLine in StringIO.StringIO(zip.read("greek_byzantine_2000_parsed_utf8.txt")): + if(verseLine.startswith('#')): + continue + verseLine = unicodedata.normalize("NFC", unicode(verseLine, 'utf-8')) + verseInfo = lineParser.match(verseLine) + if(not verseInfo): + raise Exception("Parse error on line: " + verseLine) + if(not verseInfo.group('data') or UNBOUND_CODE_TO_OSIS_CODE[verseInfo.group('book')] not in OSIS_BIBLE_BOOK_CODES): + continue + meta = verseInfo.groupdict() + + # Create book ref if it doesn't exist + if(not len(bookRefs) or bookRefs[-1].osis_id != UNBOUND_CODE_TO_OSIS_CODE[meta['book']]): + print UNBOUND_CODE_TO_OSIS_CODE[meta['book']] + + # Reset tokens + previousTokens = tokens + tokens = [] + + # Close book and chapter refs + if(len(previousTokens)): + bookRefs[-1].end_token = previousTokens[-1] + bookRefs[-1].save() + chapterRefs[-1].end_token = previousTokens[-1] + chapterRefs[-1].save() + chapterRefs = [] + verseRefs = [] + + # Set up the book ref + bookRef = Ref( + work = msWork, + type = Ref.BOOK, + osis_id = UNBOUND_CODE_TO_OSIS_CODE[meta['book']], + position = len(bookRefs), + title = OSIS_BOOK_NAMES[UNBOUND_CODE_TO_OSIS_CODE[meta['book']]] + ) + #bookRef.save() + #bookRefs.append(bookRef) + + # So here we need to have tokenParser match the entire line + pos = 0 + verseTokens = [] + while(pos < len(meta['data'])): + tokenMatch = tokenParser.match(meta['data'], pos) + if(not tokenMatch): + #print "%s %02d %02d" % (verseInfo.group('book'), int(verseInfo.group('chapter')), int(verseInfo.group('verse'))) + raise Exception("Unable to parse at position " + str(pos) + ": " + meta['data']) + + # Insert token + token = Token( + data = tokenMatch.group('word'), + type = Token.WORD, + work = msWork, + position = tokenPosition + ) + tokenPosition = tokenPosition + 1 + token.save() + tokens.append(token) + verseTokens.append(token) + + # Token Parsing + parsing = TokenParsing( + token = token, + raw = tokenMatch.group('rawParsing'), + language = Language('grc'), + work = msWork + ) + parsing.save() + + # Make this token the first in the book ref, and set the first token in the book + if len(tokens) == 1: + bookRef.start_token = tokens[0] + bookRef.save() + bookRefs.append(bookRef) + + # Set up the Chapter ref + if(not len(chapterRefs) or chapterRefs[-1].numerical_start != meta['chapter']): + if(len(chapterRefs)): + chapterRefs[-1].end_token = tokens[-2] + chapterRefs[-1].save() + chapterRef = Ref( + work = msWork, + type = Ref.CHAPTER, + osis_id = ("%s.%s" % (bookRefs[-1].osis_id, meta['chapter'])), + position = len(chapterRefs), + parent = bookRefs[-1], + numerical_start = meta['chapter'], + start_token = tokens[-1] + ) + chapterRef.save() + chapterRefs.append(chapterRef) + + pos = tokenMatch.end() + + # Create verse ref + verseRef = Ref( + work = msWork, + type = Ref.VERSE, + osis_id = ("%s.%s.%s" % (bookRefs[-1].osis_id, meta['chapter'], meta['verse'])), + position = len(verseRefs), + parent = chapterRefs[-1], + numerical_start = meta['verse'], + start_token = verseTokens[0], + end_token = verseTokens[-1] + ) + verseRef.save() + verseRefs.append(verseRef) + +#Close out the book and chapters +bookRefs[-1].end_token = tokens[-1] +bookRefs[-1].save() +chapterRefs[-1].end_token = tokens[-1] +for chapterRef in chapterRefs: + chapterRef.save() + + + diff --git a/data/manuscripts/greek_byzantine_2005_parsed.prepare_data.py b/data/manuscripts/greek_byzantine_2005_parsed.prepare_data.py new file mode 100644 index 0000000..c6fe786 --- /dev/null +++ b/data/manuscripts/greek_byzantine_2005_parsed.prepare_data.py @@ -0,0 +1,341 @@ +#!/usr/bin/python +# coding=utf8 +# Developed by Tom Brazier + +# Notes: +# 1. BYZ05CCT.ZIP contains AC24.CCT which is a variant of Acts 24:6-8. The text in +# AC.CCT, however is the same as the physical book (1st edition) so we prefer it. +# 2. BYZ05CCT.ZIP contains PA.CCT which is a variant form of the Pericope Adulterae. +# Once again, the text in JOH.CCT is the main text in the book (the variant is +# in the apparatus). So we prefer JOH.CCT. +# 3. Rev 17:8 starts in different places in the BP5 text and the CCT text, although +# the BP5 text lists the alternative starting point with parentheses. The text +# in the CCT file matches the physical book, so there's a tweak below to prefer it. + +import zipfile +import StringIO +import re +import urllib +import os + +book_names = ( + "MT", "MR", "LU", "JOH", "AC", "RO", "1CO", "2CO", "GA", "EPH", "PHP", "COL", "1TH", "2TH", + "1TI", "2TI", "TIT", "PHM", "HEB", "JAS", "1PE", "2PE", "1JO", "2JO", "3JO", "JUDE", "RE", +) + +BP5_FILE = "BP05FNL.ZIP" +CCT_FILE = "BYZ05CCT.ZIP" + +def bp5_to_unicode(bp5_word): + "Convert a word from Robinson & Pierpont's ASCII format to unicode" + # we know about all of these character translations - anything else is an error + table = u' ' * 65 + u'ΑΒΧΔΕΦΓΗΙ ΚΛΜΝΟΠΨΡΣΤΥΣΩΞΘΖ' + u' ' * 6 + u'αβχδεφγηι κλμνοπψρστυςωξθζ' + ' ' * 133 + res = bp5_word.translate(table) + assert(u' ' not in res) + return res + +def read_bp5_file(book): + """Read a book in BP5 format from BP5_FILE and turn it into a list of chapters, + each of which is a list of verses, each of which is a list of words, each of + which is a tuple starting with the unicode word and followed by one or more strongs + numbers and parsings. + + BP5 files contain the data for one book. Each verse starts on a new line with + some spaces followed by chapter and verse. There are also other line breaks. + Words are in a "preformatted ASCII" format, followed by strong number and then + parsing. More info from here: http://www.byztxt.com/downloads.html""" + + print("Coverting book %s from BP5" % book) + + bp5_zip_file = zipfile.ZipFile(BP5_FILE) + + # first pass, get all the words for all the verses + chapters = [] + for line in StringIO.StringIO(bp5_zip_file.read(book + ".BP5")): + # look for verse breaks + match = re.match(r" +([0-9]+):([0-9]+)(.*)", line) + if match: + # get chapter and verse and change line to be the remainder + chap, verse, line = (int(match.group(1)), int(match.group(2)), match.group(3)) + if chap != len(chapters): + chapters.append([]) + assert(chap == len(chapters)) + curr_verse = [] + chapters[-1].append(curr_verse) + assert(verse == len(chapters[-1])) + + # store all words for verse (these should consist of triples of greek word, strongs number and parsing) + words = line.strip().split() + curr_verse += words + + # now iterate through all verses, translating to unicode, translating parsings and putting word components together + clean_chapters = [] + word_re = re.compile(r"([a-zA-Z]+) *") + number_re = re.compile(r"([0-9]+) *") + parsing_re = re.compile(r"{([A-Z123\-]+)} *") + verse_number_re = re.compile(r" *\([0-9]+:[0-9]+\) *") + for chapter in chapters: + # work around for different starting points of Rev 17:8 (see notes at the top) + if book == "RE" and chapter is chapters[16]: + pos = chapter[6].index("(17:8)") + chapter[7] = chapter[6][pos + 1:] + chapter[7] + chapter[6] = chapter[6][:pos] + + clean_chapter = [] + for verse in chapter: + clean_verse = [] + verse = ' '.join(verse) + # marginal apparatus notes are delimited by pipe characters, strip the variants + verse = re.sub(r"\| ([^\|]*) \|[^\|]*\|", r'\1', verse) + while verse: + # occasionally (eg. Matt 23:13) an alternative verse number is inserted in brackets, ignore it + verse_number_match = verse_number_re.match(verse) + if verse_number_match: verse = verse[verse_number_match.end():] + # match word + word = [] + word_match = word_re.match(verse) + assert(word_match) + verse = verse[word_match.end():] + word.append(bp5_to_unicode(word_match.group(1))) + while True: + number_match = number_re.match(verse) + parsing_match = parsing_re.match(verse) + if not number_match and not parsing_match: break + if number_match: + verse = verse[number_match.end():] + word.append("G" + number_match.group(1)) + if parsing_match: + verse = verse[parsing_match.end():] + word.append(parsing_match.group(1)) + clean_verse.append(tuple(word)) + clean_chapter.append(clean_verse) + clean_chapters.append(clean_chapter) + + return clean_chapters + +def cct_to_unicode(bp5_word): + """Convert a word from Robinson & Pierpont's modified betacode format to unicode, and + return it along with a plain old un-accented, lowercase version for later comparison with BP5""" + + # we know about all of these character translations - anything else is an error + table = u' ' * 39 + u"'() +, ./ :; ΑΒΞΔΕΦΓΗΙ ΚΛΜΝΟΠΘΡΣΤΥ ΩΧΨΖ \ ^ αβξδεφγηι κλμνοπθρστυ ωχψζ | " + u' ' * 128 + res1 = bp5_word.translate(table) + res2 = re.sub("[^a-z,.:;]", '', bp5_word.lower()).translate(table) + assert(u' ' not in res1) + + # convert final sigmas + if res1[-1] == u'σ': res1 = res1[0:-1] + u'ς' + if res2[-1] == u'σ': res2 = res2[0:-1] + u'ς' + + # move initial accents to after the first letter so they're positioned like all other accents + res1 = re.sub(r"^([\(\)/\\\^\+\|]*)(.)", "\\2\\1", res1) + + # iterate through all accents + accent_list = [] + for match in re.finditer(r"(.)([\(\)/\\\^\+\|]+)", res1): + letter, annotations = match.groups() + accent_list.append((match.start(), match.end(), letter, annotations)) + + for match_start, match_end, letter, annotations in reversed(accent_list): + assert(letter in u'ΑΕΗΙΟΡΥΩαεηιορυω') + + # parse breathings, accents, etc. + smooth_breathing = ")" in annotations + rough_breathing = "(" in annotations + assert(smooth_breathing + rough_breathing <= 1) + diaeresis = "+" in annotations + iota_subscript = "|" in annotations + acute_accent = "/" in annotations + grave_accent = "\\" in annotations + circumflex_accent = "^" in annotations + assert(acute_accent + grave_accent + circumflex_accent <= 1) + + # do some useful preprocessing of the letter + is_upper_case = letter in u'ΑΕΗΙΟΡΥΩ' + lower_case = {u'Α':u'α', u'Ε':u'ε', u'Η':u'η', u'Ι':u'ι', u'Ο':u'ο', u'Î¥':u'υ', u'Ω':u'ω'}.get(letter, letter) + + # rho is easy + if letter in u'Ρρ': + assert(annotations == "(") + res1 = res1[:match_start] + {u'Ρ':u'Ῥ', u'ρ':u'á¿¥'}[letter] + res1[match_end:] + continue + + # diaeresis is easy + if diaeresis: + offset = acute_accent * 1 + circumflex_accent * 5 + letter = {u'ι':u'ῒ', u'υ':u'á¿¢'}[letter] + letter = unichr(ord(letter) + offset) + res1 = res1[:match_start] + letter + res1[match_end:] + continue + + # unicode has a very nice tabular encoding for vowels with breathings + if smooth_breathing or rough_breathing: + offset = rough_breathing * 1 + grave_accent * 2 + acute_accent * 4 + circumflex_accent * 4 + is_upper_case * 8 + if iota_subscript: + letter = {u'α':u'ᾀ', u'η':u'ᾐ', u'ω':u'á¾ '}[lower_case] + else: + letter = {u'α':u'ἀ', u'ε':u'ἐ', u'η':u'á¼ ', u'ι':u'á¼°', u'ο':u'ὀ', u'υ':u'ὐ', u'ω':u'á½ '}[lower_case] + letter = unichr(ord(letter) + offset) + res1 = res1[:match_start] + letter + res1[match_end:] + continue + + # now we can clean up the remaining iota subscripts + if iota_subscript and not is_upper_case: + offset = grave_accent * -1 + acute_accent * 1 + circumflex_accent * 4 + letter = {u'α':u'á¾³', u'η':u'ῃ', u'ω':u'ῳ'}[letter] + letter = unichr(ord(letter) + offset) + res1 = res1[:match_start] + letter + res1[match_end:] + continue + + # now we can clean up the remaining lower-case acutes and graves + if (grave_accent or acute_accent) and not is_upper_case: + offset = acute_accent * 1 + offset += {u'α':0, u'ε':2, u'η':4, u'ι':6, u'ο':8, u'υ':10, u'ω':12}[lower_case] + letter = unichr(ord(u'á½°') + offset) + res1 = res1[:match_start] + letter + res1[match_end:] + continue + + # and the remaining circumflexes and upper-case acutes and graves + if circumflex_accent and not is_upper_case or (grave_accent or acute_accent) and is_upper_case: + assert(letter not in u'εο') + offset = grave_accent * 4 + acute_accent * 5 + offset += {u'α':0, u'ε':14, u'η':16, u'ι':32, u'ο':62, u'υ':48, u'ω':64}[lower_case] + letter = unichr(ord(u'á¾¶') + offset) + res1 = res1[:match_start] + letter + res1[match_end:] + continue + + # we ought to have covered all cases now + assert(False) + + # make sure we got all the accents + assert(not re.match(u'.*[\(\)/\\\^\+\|]', res1)) + return (res1, res2) + +def read_cct_file(book): + """Read a book in CCT format from CCT_FILE and turn it into a list of chapters, + each of which is a list of verses, each of which is a list of accented words and + punctuation marks. + + CCT files contain the data for one book. There is exactly one line per verse. + Words are in a a modified betacode format. More info from here: + http://www.byztxt.com/downloads.html""" + + print("Coverting book %s from CCT" % book) + + cct_zip_file = zipfile.ZipFile(CCT_FILE) + + # run through the lines, building chapters + chapters = [] + for line in StringIO.StringIO(cct_zip_file.read(book + ".CCT")): + # ignore comment lines + if line[0] == "#": continue + + # strip the variant readings and paragraph breaks + line = re.sub(r" *\{[^\}]*} *", ' ', line) + + # strip hyphens from the text + line = re.sub(r" *- *", ' ', line) + + # every line is a new verse, so get the chapter and verse numbers + match = re.match(r" +([0-9]+):([0-9]+)(.*)", line) + assert(match) + chap, verse, line = (int(match.group(1)), int(match.group(2)), match.group(3)) + + # build the verse + line = re.sub(r"([,.:;])", r" \1", line) + curr_verse = [cct_to_unicode(word) for word in line.strip().split()] + + # append chapters and verses + if chap != len(chapters): + chapters.append([]) + assert(chap == len(chapters)) + chapters[-1].append(curr_verse) + assert(verse == len(chapters[-1])) + + return chapters + +if(not os.path.exists('BP05FNL.ZIP')): + print("Downloading BP05FNL.ZIP") + urllib.urlretrieve("http://koti.24.fi/jusalak/GreekNT/BP05FNL.ZIP", "BP05FNL.ZIP") + +if(not os.path.exists('BYZ05CCT.ZIP')): + print("Downloading BYZ05CCT.ZIP") + urllib.urlretrieve("http://koti.24.fi/jusalak/GreekNT/BYZ05CCT.ZIP", "BYZ05CCT.ZIP") + +books = [] +for book_name in book_names: + bp5_chapters = read_bp5_file(book_name) + print bp5_chapters[0][0] + print ' '.join(word[0] for word in bp5_chapters[0][0]) + cct_chapters = read_cct_file(book_name) + print ' '.join(word[1] for word in cct_chapters[0][0]) + assert(len(bp5_chapters) == len(cct_chapters)) + books.append((bp5_chapters, cct_chapters)) + +# generate output +print("Generating output files") +outfile_plain = file("greek_byzantine_2005_parsed_utf8.txt", "wb") +outfile_plain.write( +"""#name\tGreek NT: Byzantine/Majority Text (2005) [Parsed] +#filetype\tUnmapped-BCVS +#copyright\tSee http://www.byztxt.com/ +#abbreviation\t +#language\tgko +#note\t +#columns\torig_book_index\torig_chapter\torig_verse\torder_by\ttext +""") + +outfile_punc = file("greek_byzantine_2005_parsed_punc_utf8.txt", "wb") +outfile_punc.write( +"""#name\tGreek NT: Byzantine/Majority Text (2005) [Parsed with punctuation, accents and breathings] +#filetype\tUnmapped-BCVS +#copyright\tSee http://www.byztxt.com/ +#abbreviation\t +#language\tgko +#note\t +#columns\torig_book_index\torig_chapter\torig_verse\torder_by\ttext +""") + +ordering = 0 +for i_book in range(len(books)): + print("Book: %s" % book_names[i_book]) + bp5_chapters, cct_chapters = books[i_book] + for i_chap in range(len(bp5_chapters)): + bp5_chapter = bp5_chapters[i_chap] + cct_chapter = cct_chapters[i_chap] + assert(len(bp5_chapter) == len(cct_chapter)) + for i_verse in range(len(bp5_chapter)): + bp5_verse = bp5_chapter[i_verse] + cct_verse = cct_chapter[i_verse] + + # run through the verse building the output line + out_words_punc = [] + out_words_plain = [] + i_bp5_word = i_cct_word = 0 + while i_bp5_word < len(bp5_verse) or i_cct_word < len(cct_verse): + if i_bp5_word < len(bp5_verse): bp5_word = bp5_verse[i_bp5_word] + if not i_cct_word < len(cct_verse): print i_chap, i_verse, i_cct_word, i_bp5_word, len(cct_verse), len(bp5_verse) + cct_word = cct_verse[i_cct_word] + if cct_word[0] in ",.:;": + out_words_punc.append(cct_word[0]) + i_cct_word += 1 + else: + # ensure that we're in sync, i.e. that the unadorned CCT word is the same as the BP5 word + assert(cct_word[1] == bp5_word[0]) + out_words_punc.append(cct_word[0]) + out_words_punc += bp5_word[1:] + out_words_plain.append(cct_word[1]) + out_words_plain += bp5_word[1:] + i_bp5_word += 1 + i_cct_word += 1 + ordering += 10 + out_line = u"%dN\t%d\t%d\t\t%d\t" % (i_book + 40, i_chap + 1, i_verse + 1, ordering) + out_line += u"%s\n" % u' '.join(out_words_plain) + outfile_plain.write(out_line.encode('utf8')) + + out_line = u"%dN\t%d\t%d\t\t%d\t" % (i_book + 40, i_chap + 1, i_verse + 1, ordering) + out_line += u"%s\n" % u' '.join(out_words_punc) + outfile_punc.write(out_line.encode('utf8')) + +del(outfile_plain) +del(outfile_punc) diff --git a/data/manuscripts/greek_byzantine_2005_parsed.py b/data/manuscripts/greek_byzantine_2005_parsed.py new file mode 100644 index 0000000..d42fc26 --- /dev/null +++ b/data/manuscripts/greek_byzantine_2005_parsed.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python +# encoding: utf-8 + +msID = 9 + +import sys, os, re, unicodedata +from datetime import date +from django.core.management import setup_environ +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) #There's probably a better way of doing this +from openscriptures import settings +setup_environ(settings) +from openscriptures.data.unbound_bible import UNBOUND_CODE_TO_OSIS_CODE # Why does this have to be explicit? +from openscriptures.core.models import * +from openscriptures.data import import_helpers + +# Abort if MS has already been added (and --force not supplied) +import_helpers.abort_if_imported(msID) + +# First step is to fetch the data from the server via script by Tom Brazier which converts the source from Betacode to Unicode and the Unbound Bible file format +if(not os.path.exists('greek_byzantine_2005_parsed_punc_utf8.txt')): + execfile('greek_byzantine_2005_parsed.prepare_data.py') + +import_helpers.delete_work(msID) +msWork = Work( + id = msID, + title = "Byzantine/Majority Text (2005)", + description = "Parsed with punctuation, accents and breathings", + abbreviation = 'Byz-2005', + language = Language('grc'), + type = 'Bible', + osis_slug = 'Byzantine', + publish_date = date(2005, 1, 1), + originality = 'manuscript-edition', + creator = "Maurice A. Robinson and William G. Pierpont.", + url = "http://www.byztxt.com/download/BYZ05CCT.ZIP", + license = License.objects.get(url="http://creativecommons.org/licenses/publicdomain/") +) +msWork.save() + +# The followig regular epression identifies the parts of the following line: +#40N 1 1 10 Βίβλος G976 N-NSF γενέσεως G1078 N-GSF Ἰησοῦ G2424 N-GSM χριστοῦ G5547 N-GSM , υἱοῦ G5207 N-GSM Δαυίδ G1138 N-PRI , υἱοῦ G5207 N-GSM Ἀβραάμ G11 N-PRI . +lineParser = re.compile(ur"""^ + (?P<book>\d+\w+)\t+ # Unbound Bible Code + (?P<chapter>\d+)\t+ # Chapter + (?P<verse>\d+)\t+ # Verse + \d+\t+ # Ignore orderby column + (?P<data>.*?) + \s*$""", + re.VERBOSE +) + +# Regular expression to parse each individual word on a line (the data group from above) +# Ὃ G3739 R-ASN ἤν G1510 G5707 V-IAI-3S ἀπ' G575 PREP ἀρχῆς G746 N-GSF , ὃ G3739 R-ASN ἀκηκόαμεν G191 G5754 V-2RAI-1P-ATT , ὃ G3739 R-ASN ἑωράκαμεν G3708 G5758 V-RAI-1P-ATT τοῖς G3588 T-DPM ὀφθαλμοῖς G3788 N-DPM ἡμῶν G1473 P-1GP , ὃ G3739 R-ASN ἐθεασάμεθα G2300 G5662 V-ADI-1P , καὶ G2532 CONJ αἱ G3588 T-NPF χεῖρες G5495 N-NPF ἡμῶν G1473 P-1GP ἐψηλάφησαν G5584 G5656 V-AAI-3P περὶ G4012 PREP τοῦ G3588 T-GSM λόγου G3056 N-GSM τῆς G3588 T-GSF ζωῆς G2222 N-GSF . +tokenParser = re.compile(ur""" + (?P<word>\S+)\s+ + (?P<rawParsing> + G?\d+ + (?: \s+G?\d+ | \s+[A-Z0-9\-:]+ )+ + ) + (?: + \s+(?P<punctuation>[%s]) + )? + (?:\s+ | \s*$ ) + """ % re.escape(ur""".·,;:!?"'"""), + re.VERBOSE | re.UNICODE) + +bookRefs = [] +chapterRefs = [] +verseRefs = [] +tokens = [] +previousTokens = [] +tokenPosition = 0 + +f = open('greek_byzantine_2005_parsed_punc_utf8.txt', 'r') +for verseLine in f: + if(verseLine.startswith('#')): + continue + verseLine = unicodedata.normalize("NFC", unicode(verseLine, 'utf-8')) + verseInfo = lineParser.match(verseLine) + if(not verseInfo): + raise Exception("Parse error on line: " + verseLine) + if(not verseInfo.group('data') or UNBOUND_CODE_TO_OSIS_CODE[verseInfo.group('book')] not in OSIS_BIBLE_BOOK_CODES): + continue + meta = verseInfo.groupdict() + + # Create book ref if it doesn't exist + if(not len(bookRefs) or bookRefs[-1].osis_id != UNBOUND_CODE_TO_OSIS_CODE[meta['book']]): + print UNBOUND_CODE_TO_OSIS_CODE[meta['book']] + + # Reset tokens + previousTokens = tokens + tokens = [] + + # Close book and chapter refs + if(len(previousTokens)): + bookRefs[-1].end_token = previousTokens[-1] + bookRefs[-1].save() + chapterRefs[-1].end_token = previousTokens[-1] + chapterRefs[-1].save() + chapterRefs = [] + verseRefs = [] + + # Set up the book ref + bookRef = Ref( + work = msWork, + type = Ref.BOOK, + osis_id = UNBOUND_CODE_TO_OSIS_CODE[meta['book']], + position = len(bookRefs), + title = OSIS_BOOK_NAMES[UNBOUND_CODE_TO_OSIS_CODE[meta['book']]] + ) + #bookRef.save() + #bookRefs.append(bookRef) + + # So here we need to have tokenParser match the entire line + pos = 0 + verseTokens = [] + while(pos < len(meta['data'])): + tokenMatch = tokenParser.match(meta['data'], pos) + if(not tokenMatch): + print "%s %02d %02d" % (meta['book'], int(meta['chapter']), int(meta['verse'])) + print "Unable to parse at position " + str(pos) + ": " + meta['data'] + raise Exception("Unable to parse at position " + str(pos) + ": " + meta['data']) + + # Insert token + token = Token( + data = tokenMatch.group('word'), + type = Token.WORD, + work = msWork, + position = tokenPosition + ) + tokenPosition = tokenPosition + 1 + token.save() + tokens.append(token) + verseTokens.append(token) + + # Insert punctuation + if(tokenMatch.group('punctuation')): + token = Token( + data = tokenMatch.group('punctuation'), + type = Token.PUNCTUATION, + work = msWork, + position = tokenPosition + ) + tokenPosition = tokenPosition + 1 + token.save() + tokens.append(token) + verseTokens.append(token) + + # Token Parsing + #strongs = [tokenMatch.group('strongs1')] + #if(tokenMatch.group('strongs2')): + # strongs.append(tokenMatch.group('strongs2')) + parsing = TokenParsing( + token = token, + raw = tokenMatch.group("rawParsing"), + #parse = tokenMatch.group('parsing'), + #strongs = ";".join(strongs), + language = Language('grc'), + work = msWork + ) + parsing.save() + + # Make this token the first in the book ref, and set the first token in the book + if len(tokens) == 1: + bookRef.start_token = tokens[0] + bookRef.save() + bookRefs.append(bookRef) + + # Set up the Chapter ref + if(not len(chapterRefs) or chapterRefs[-1].numerical_start != meta['chapter']): + if(len(chapterRefs)): + chapterRefs[-1].end_token = tokens[-2] + chapterRefs[-1].save() + chapterRef = Ref( + work = msWork, + type = Ref.CHAPTER, + osis_id = ("%s.%s" % (bookRefs[-1].osis_id, meta['chapter'])), + position = len(chapterRefs), + parent = bookRefs[-1], + numerical_start = meta['chapter'], + start_token = tokens[-1] + ) + chapterRef.save() + chapterRefs.append(chapterRef) + + pos = tokenMatch.end() + + # Create verse ref + verseRef = Ref( + work = msWork, + type = Ref.VERSE, + osis_id = ("%s.%s.%s" % (bookRefs[-1].osis_id, meta['chapter'], meta['verse'])), + position = len(verseRefs), + parent = chapterRefs[-1], + numerical_start = meta['verse'], + start_token = verseTokens[0], + end_token = verseTokens[-1] + ) + verseRef.save() + verseRefs.append(verseRef) + +#Save all books, chapters +bookRefs[-1].end_token = tokens[-1] +bookRefs[-1].save() +chapterRefs[-1].end_token = tokens[-1] +for chapterRef in chapterRefs: + chapterRef.save() + + +f.close() diff --git a/data/manuscripts/greek_textus_receptus_parsed.py b/data/manuscripts/greek_textus_receptus_parsed.py new file mode 100644 index 0000000..eab4027 --- /dev/null +++ b/data/manuscripts/greek_textus_receptus_parsed.py @@ -0,0 +1,609 @@ +#!/usr/bin/env python +# encoding: utf-8 + +# TODO: Not inserting refs for TR2, and not inserting enough VGTs + +msID = 6 +varMsID = 7 + +import sys, os, re, unicodedata, difflib, urllib, zipfile, StringIO +from datetime import date +from django.core.management import setup_environ +from django.utils.encoding import smart_str, smart_unicode +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) #There's probably a better way of doing this +from openscriptures import settings +setup_environ(settings) +from openscriptures.data.unbound_bible import UNBOUND_CODE_TO_OSIS_CODE # Why does this have to be explicit? +from openscriptures.data import import_helpers +from openscriptures.core.models import * + +# Abort if MS has already been added (and --force not supplied) +import_helpers.abort_if_imported(msID) + +# Download the source file +source_url = "http://www.unboundbible.org/downloads/bibles/greek_textus_receptus_parsed.zip" +import_helpers.download_resource(source_url) + +# Delete existing works and their contents +import_helpers.delete_work(msID, varMsID) + +msWork = Work( + id = msID, + title = "Textus Receptus (1551)", + abbreviation = "TR-1551", + language = Language('grc'), + type = 'Bible', + osis_slug = 'Steph', + publish_date = date(1551, 1, 1), + originality = 'manuscript-edition', + creator = "By <a href='http://en.wikipedia.org/wiki/Desiderius_Erasmus' title='Desiderius Erasmus @ Wikipedia'>Desiderius Erasmus</a>. Edited by <a href='http://en.wikipedia.org/wiki/Robert_Estienne' title='Robert Estienne @ Wikipedia'>Robert Estienne</a>.", + url = source_url, + #variant_number = 1, + license = License.objects.filter(url="http://creativecommons.org/licenses/publicdomain/")[0] +) +msWork.save() + +varGroup1 = VariantGroup( + work = msWork, + primacy = 0 +) +varGroup1.save() + +# Now we need to create additional works for each set of variants that this work contains +# Diff/variant works will have tokens that have positions that are the same as those in the base work? The base work's tokens will have positions that have gaps? +# When processing a line with enclosed variants, it will be important to construct the verse for VAR1, VAR2, etc... and then merge these together. +variantWork = Work( + id = varMsID, + title = "Textus Receptus (1894)", + abbreviation = "TR-1894", + language = Language('grc'), + type = 'Bible', + osis_slug = 'Scrivener', + publish_date = date(1894, 1, 1), + originality = 'manuscript-edition', + creator = "By <a href='http://en.wikipedia.org/wiki/Desiderius_Erasmus' title='Desiderius Erasmus @ Wikipedia'>Desiderius Erasmus</a>. Edited by <a href='http://en.wikipedia.org/wiki/Robert_Estienne' title='Robert Estienne @ Wikipedia'>Robert Estienne</a>, and <a href='http://en.wikipedia.org/wiki/Frederick_Henry_Ambrose_Scrivener' title='Frederick Henry Ambrose Scrivener @ Wikipedia'>F. H. A. Scrivener</a>.", + url = "http://www.unboundbible.org/downloads/bibles/greek_textus_receptus_parsed.zip", + base = msWork, + #variant_number = 2, + license = License.objects.filter(url="http://creativecommons.org/licenses/publicdomain/")[0] +) +variantWork.save() + +varGroup2 = VariantGroup( + work = variantWork, + primacy = 0 +) +varGroup2.save() + +works = [msWork, variantWork] +variantGroups = [varGroup1, varGroup2] + +# The followig regular epression identifies the parts of the following line: +# 40N 1 1 10 Βίβλος G976 N-NSF γενέσεως G1078 N-GSF Ἰησοῦ G2424 N-GSM χριστοῦ G5547 N-GSM , υἱοῦ G5207 N-GSM Δαυίδ G1138 N-PRI , υἱοῦ G5207 N-GSM Ἀβραάμ G11 N-PRI . +lineParser = re.compile(ur"""^ + (?P<book>\d+\w+)\t+ # Unbound Bible Code + (?P<chapter>\d+)\t+ # Chapter + (?P<verse>\d+)\t+ # Verse + \d+\t+ # Ignore orderby column + (?P<data>.*?) + \s*$""", + re.VERBOSE +) + +# Regular expression to parse each individual word on a line (the data group from above) +tokenParser = re.compile(ur""" + (?P<word>ινα\s+τι|\S+)\s+ + (?P<rawParsing> + G?\d+ + (?: \s+G?\d+ | \s+[A-Z0-9\-:]+ )+ + ) + (?:\s+|$) + """, + re.VERBOSE | re.UNICODE) + +# Compile the regular expressions that are used to isolate the variants for each work +reFilterVar = [ + re.compile(ur"\s* ( {VAR[^1]:.+?} | {VAR1: | } )""", re.VERBOSE), + re.compile(ur"\s* ( {VAR[^2]:.+?} | {VAR2: | } )""", re.VERBOSE) +] +reHasVariant = re.compile(ur'{VAR') +reHasBracket = re.compile(ur'\[|\]') + +bookRefs = [[], []] +chapterRefs = [[], []] +verseRefs = [[], []] +tokens = [] + + +class PlaceholderToken(dict): + """ + Contains a regular expression match for a work; used for collating two + works' variants and merging them together before insertion into model + """ + + def __init__(self, **args): + for key in args: + self[key] = args[key] + + def __setattr__(self, key, val): + self[key] = val + + def __getattr__(self, key): + return self[key] + + def establish(self): + """ + This can take the values and turn this into a real token... and then + also create the many-to-many relationships. Return the new token? + """ + + token = Token( + data = self.data, + type = self.type, + position = self.position, + certainty = None, #self.certainty; handled by VariantGroupToken + work = workTNT1 + ) + #for key in self: + # if key not in ('variant_group', 'certainty'): + # token[key] = self[key] + token.save() + + vgt = VariantGroupToken( + token = token, + variant_group = self.variant_group, + certainty = self.certainty + ) + vgt.save() + return token + + def __hash__(self): + return hash(unicode(self)) + + def __eq__(self, other): + return unicode(self) == unicode(other) + + #def __str__(self): + # return unicode(self) + def __unicode__(self): + #return ("[" * self['certainty']) + self['data'] + ("]" * self['certainty']) + return import_helpers.normalize_token(self['data']) + + +def verseTokens(): #No need to do generator here? + """ + Fetch the next token in the verse. + """ + global works, variantGroups + previousVerseMeta = {'book':'', 'chapter':'', 'verse':''} + bookCount = 0 + chapterCount = 0 + verseCount = 0 + openBracketsCount = [0, 0] + + zip = zipfile.ZipFile(os.path.basename(source_url)) + for verseLine in StringIO.StringIO(zip.read("greek_textus_receptus_parsed_utf8.txt")): + if(verseLine.startswith('#')): + continue + verseLine = unicodedata.normalize("NFC", smart_unicode(verseLine)) + verseInfo = lineParser.match(verseLine) + if(not verseInfo): + raise Exception("Parse error on line: " + verseLine) + if(not verseInfo.group('data') or UNBOUND_CODE_TO_OSIS_CODE[verseInfo.group('book')] not in OSIS_BIBLE_BOOK_CODES): + continue + meta = verseInfo.groupdict() + + newBook, newChapter, newVerse = False, False, False + if previousVerseMeta['book'] != meta['book']: + bookCount += 1 + newBook = True + if previousVerseMeta['book'] != meta['book'] or previousVerseMeta['chapter'] != meta['chapter']: + chapterCount += 1 + newChapter = True + if previousVerseMeta['verse'] != meta['verse']: + verseCount += 1 + newVerse = True + + for i in (0,1): + # Construct the Book ref if it is not the same as the previous + if newBook: + print OSIS_BOOK_NAMES[UNBOUND_CODE_TO_OSIS_CODE[meta['book']]] + bookRef = Ref( + type = Ref.BOOK, + osis_id = UNBOUND_CODE_TO_OSIS_CODE[meta['book']], + title = OSIS_BOOK_NAMES[UNBOUND_CODE_TO_OSIS_CODE[meta['book']]], + work = works[i], + position = bookCount, + #numerical_start = bookCount + ) + yield bookRef + + # Construct the Chapter ref if it is not the same as the previous or if the book is different (matters for single-chapter books) + if newChapter: + chapterRef = Ref( + type = Ref.CHAPTER, + osis_id = bookRef.osis_id + '.' + meta['chapter'], + numerical_start = meta['chapter'], + work = works[i], + position = chapterCount + ) + yield chapterRef + + # Construct the Verse ref if it is not the same as the previous (note there are no single-verse books) + if newVerse: + verseRef = Ref( + type = Ref.VERSE, + osis_id = chapterRef.osis_id + '.' + meta['verse'], + numerical_start = meta['verse'], + work = works[i], + position = verseCount + ) + yield verseRef + + #end for i in (0,1): + previousVerseMeta = meta + + + # Parse words for both variants, or if there are open brackets or if this verse has brackets, then we need to do some special processing + # Regarding two editions having identical variants but differing degrees of assurance: we will have to not insert them as Token(variant_group=None) but rather + # as two tokens at the same position with different variant_groups and different certainties: + # Token(variant_group=1, position=X, certainty=0) + # Token(variant_group=2, position=X, certainty=1) + if((openBracketsCount[0] or openBracketsCount[1]) or reHasVariant.search(meta['data']) or reHasBracket.search(meta['data'])): + + verseTokensVars = [[], []] + for i in (0,1): + verseVar = reFilterVar[i].sub('', meta['data']).strip() + verseTokensVar = [] + pos = 0 + while(pos < len(verseVar)): + tokenMatch = tokenParser.match(verseVar, pos) + if not tokenMatch: + raise Exception("Parse error") + token = PlaceholderToken( + data = tokenMatch.group('word'), + type = Token.WORD, + work = msWork, + variant_group = variantGroups[i] + ) + #token = TokenContainer(tokenMatch.groupdict(), 0) + + # Determine if this token is within brackets + if(re.search(r'\[\[', verseVar[tokenMatch.start() : tokenMatch.end()])): + openBracketsCount[i] = 2 + elif(re.search(r'\[', verseVar[tokenMatch.start() : tokenMatch.end()])): + openBracketsCount[i] = 1 + token.certaunty = openBracketsCount[i] + + # Determine if this token is the last one in brackets + if(re.search(r'\]', verseVar[tokenMatch.start() : tokenMatch.end()])): + openBracketsCount[i] = 0 + + verseTokensVars[i].append(token) + pos = tokenMatch.end() + + # Now merge verseTokensVar[0] and verseTokensVar[1] into verseTokens, and then set each token's position according to where it was inserted + # 'replace' a[i1:i2] should be replaced by b[j1:j2]. + # 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. + # 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. + # 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). + # However, we need to not set variant_group to None if the certainty is not the same!!! + diffedTokenMatches = difflib.SequenceMatcher(None, verseTokensVars[0], verseTokensVars[1]) + for opcode in diffedTokenMatches.get_opcodes(): + if(opcode[0] == 'equal'): + var1indicies = range(opcode[1], opcode[2]) + var2indicies = range(opcode[3], opcode[4]) + + while(len(var1indicies)): + i = var1indicies.pop(0) + j = var2indicies.pop(0) + + # If the two variants are identical even in the open bracket count, then only insert one and set + # variant_group to None because there is absolutely no variance + if(verseTokensVar[0][i].open_brackets == verseTokensVar[1][j].open_brackets): + yield verseTokensVar[0][i] + # The open_bracket count in the two tokens is different, so insert both but at the exact same position + else: + yield verseTokensVar[0][i] + yield verseTokensVar[1][j] + elif(opcode[0] == 'delete'): + for i in range(opcode[1], opcode[2]): + yield verseTokensVar[0][i] + elif(opcode[0] == 'insert'): + for i in range(opcode[3], opcode[4]): + yield verseTokensVar[1][i] + elif(opcode[0] == 'replace'): + for i in range(opcode[1], opcode[2]): + yield verseTokensVar[0][i] + for i in range(opcode[3], opcode[4]): + yield verseTokensVar[1][i] + + # No variants and there weren't any variant brackets, so just parse them out of one verse + else: + pos = 0 + while(pos < len(meta['data'])): + tokenMatch = tokenParser.match(meta['data'], pos) + if(not tokenMatch): + raise Exception("Unable to parse at position " + str(pos) + ": " + verseInfo.group('data')) + token = PlaceholderToken( + data = tokenMatch.group('word'), + type = Token.WORD, + work = msWork, + variant_group = None + ) + yield token + #tokenContainers.append(TokenContainer(tokenMatch.groupdict(), None)) + #tokenContainers.append(TokenContainer(tokenMatch.groupdict(), 0)) + #tokenContainers.append(TokenContainer(tokenMatch.groupdict(), 1)) + pos = tokenMatch.end() + + return + + +count = 0 +for token in verseTokens(): + if isinstance(token, Ref): + print "Ref: " + str(token) + else: + print " - " + token.data + " " + + count += 1 + if count == 20: + break; + + + + + +tokenPosition = 0 + +exit(1) + + + + + + + + + + + + + + + + + + + + + + + + + + +zip = zipfile.ZipFile(os.path.basename(source_url)) +for verseLine in StringIO.StringIO(zip.read("greek_textus_receptus_parsed_utf8.txt")): + if(verseLine.startswith('#')): + continue + verseLine = unicodedata.normalize("NFC", smart_unicode(verseLine)) + verseInfo = lineParser.match(verseLine) + if(not verseInfo): + raise Exception("Parse error on line: " + verseLine) + if(not verseInfo.group('data') or UNBOUND_CODE_TO_OSIS_CODE[verseInfo.group('book')] not in OSIS_BIBLE_BOOK_CODES): + continue + meta = verseInfo.groupdict() + + # Not only do we need to handle {VARX: } but also [variant blocks] + # Here we need to fix bracketed words (find the span and then add them around each individual word contained in the span) + + tokenContainers = [] + verseTokens = [] + + # Parse words for both variants, or if there are open brackets or if this verse has brackets, then we need to do some special processing + # Regarding two editions having identical variants but differing degrees of assurance: we will have to not insert them as Token(variant_group=None) but rather + # as two tokens at the same position with different variant_groups and different certainties: + # Token(variant_group=1, position=X, certainty=0) + # Token(variant_group=2, position=X, certainty=1) + if((var1OpenBrackets or var2OpenBrackets) or reHasVariant.search(meta['data']) or reHasBracket.search(meta['data'])): + + # Get the tokens from the first variant + verseVar1 = reFilterVar1.sub('', meta['data']).strip() + verseTokensVar1 = [] + pos = 0 + while(pos < len(verseVar1)): + tokenMatch = tokenParser.match(verseVar1, pos) + if(not tokenMatch): + print "at " + str(pos) + ": " + verseVar1 + raise Exception("Parse error") + token = TokenContainer(tokenMatch.groupdict(), 0) + + # Determine if this token is within brackets + if(re.search(r'\[\[', verseVar1[tokenMatch.start() : tokenMatch.end()])): + var1OpenBrackets = 2 + elif(re.search(r'\[', verseVar1[tokenMatch.start() : tokenMatch.end()])): + var1OpenBrackets = 1 + token.open_brackets = var1OpenBrackets + + # Determine if this token is the last one in brackets + if(re.search(r'\]', verseVar1[tokenMatch.start() : tokenMatch.end()])): + var1OpenBrackets = 0 + + verseTokensVar1.append(token) + pos = tokenMatch.end() + + # Get the tokens from the second variant + verseVar2 = reFilterVar2.sub('', meta['data']).strip() + verseTokensVar2 = [] + pos = 0 + while(pos < len(verseVar2)): + tokenMatch = tokenParser.match(verseVar2, pos) + if(not tokenMatch): + print "at " + str(pos) + ": " + verseVar2 + raise Exception("Parse error") + token = TokenContainer(tokenMatch.groupdict(), 1) + + # Determine if this token is within brackets + if(re.search(r'\[\[', verseVar2[tokenMatch.start() : tokenMatch.end()])): + var2OpenBrackets = 2 + elif(re.search(r'\[', verseVar2[tokenMatch.start() : tokenMatch.end()])): + var2OpenBrackets = 1 + token.open_brackets = var2OpenBrackets + + # Determine if this token is the last one in brackets + if(re.search(r'\]', verseVar2[tokenMatch.start() : tokenMatch.end()])): + var2OpenBrackets = 0 + + verseTokensVar2.append(token) + pos = tokenMatch.end() + + # Now merge verseTokensVar1 and verseTokensVar2 into verseTokens, and then set each token's position according to where it was inserted + # 'replace' a[i1:i2] should be replaced by b[j1:j2]. + # 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. + # 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. + # 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). + # However, we need to not set variant_group to None if the certainty is not the same!!! + diffedTokenMatches = difflib.SequenceMatcher(None, verseTokensVar1, verseTokensVar2) + for opcode in diffedTokenMatches.get_opcodes(): + if(opcode[0] == 'equal'): + var1indicies = range(opcode[1], opcode[2]) + var2indicies = range(opcode[3], opcode[4]) + + while(len(var1indicies)): + i = var1indicies.pop(0) + j = var2indicies.pop(0) + + # If the two variants are identical even in the open bracket count, then only insert one and set + # variant_group to None because there is absolutely no variance + if(verseTokensVar1[i].open_brackets == verseTokensVar2[j].open_brackets): + verseTokensVar1[i].variant_group = None + verseTokensVar1[i].index = None + tokenContainers.append(verseTokensVar1[i]) + # The open_bracket count in the two tokens is different, so insert both but at the exact same position + else: + tokenContainers.append(verseTokensVar1[i]) + tokenContainers.append(verseTokensVar2[j]) + elif(opcode[0] == 'delete'): + for i in range(opcode[1], opcode[2]): + tokenContainers.append(verseTokensVar1[i]) + elif(opcode[0] == 'insert'): + for i in range(opcode[3], opcode[4]): + tokenContainers.append(verseTokensVar2[i]) + elif(opcode[0] == 'replace'): + for i in range(opcode[1], opcode[2]): + tokenContainers.append(verseTokensVar1[i]) + for i in range(opcode[3], opcode[4]): + tokenContainers.append(verseTokensVar2[i]) + + # No variants and there weren't any variant brackets, so just parse them out of one verse + else: + pos = 0 + while(pos < len(meta['data'])): + tokenMatch = tokenParser.match(meta['data'], pos) + if(not tokenMatch): + raise Exception("Unable to parse at position " + str(pos) + ": " + verseInfo.group('data')) + tokenContainers.append(TokenContainer(tokenMatch.groupdict(), None)) + #tokenContainers.append(TokenContainer(tokenMatch.groupdict(), 0)) + #tokenContainers.append(TokenContainer(tokenMatch.groupdict(), 1)) + pos = tokenMatch.end() + + # Create book ref if it doesn't exist + if(not len(bookRefs) or bookRefs[-1].osis_id != UNBOUND_CODE_TO_OSIS_CODE[meta['book']]): + print UNBOUND_CODE_TO_OSIS_CODE[meta['book']] + + # Set up the book ref + for i in (0,1): + bookRef = Ref( + work = works[i], + type = Ref.BOOK, + osis_id = UNBOUND_CODE_TO_OSIS_CODE[meta['book']], + position = len(bookRefs[i]), + title = OSIS_BOOK_NAMES[UNBOUND_CODE_TO_OSIS_CODE[meta['book']]] + ) + bookRefs[i].append(bookRef) + + # Now process the tokens like normal + verseTokens = [] + + lastTokenContainer = None + for tokenContainer in tokenContainers: + + # Only do this if the previous token is different than this token + if not lastTokenContainer or lastTokenContainer.position != tokenContainer.position or lastTokenContainer.match['word'] != tokenContainer.match['word']: + token = Token( + data = tokenContainer.match['word'], + type = Token.WORD, + work = msWork, + position = tokenContainer.position, + #variant_group = tokenContainer.variant_group, + certainty = tokenContainer.open_brackets + ) + token.save() + tokens.append(token) + verseTokens.append(token) + + # Associate the token its respective variant group if it has one + if tokenContainer.variant_group: + vgt = VariantGroupToken( + variant_group = tokenContainer.variant_group, + token = tokens[-1], + certainty = tokenContainer.open_brackets + ) + vgt.save() + + # Token Parsing + #strongs = [tokenContainer.match['strongs1']] + #if(tokenContainer.match['strongs2']): + # strongs.append(tokenContainer.match['strongs2']) + parsing = TokenParsing( + token = token, + raw = tokenContainer.match['rawParsing'], + #parse = tokenContainer.match['parsing'], + #strongs = ";".join(strongs), + language = Language('grc'), + work = msWork + ) + parsing.save() + + # Set up the Chapter ref + if(not len(chapterRefs) or chapterRefs[-1].numerical_start != meta['chapter']): + if(len(chapterRefs)): + chapterRefs[-1].end_token = tokens[-2] + chapterRefs[-1].save() + chapterRef = Ref( + work = msWork, + type = Ref.CHAPTER, + osis_id = ("%s.%s" % (bookRefs[-1].osis_id, meta['chapter'])), + position = len(chapterRefs), + parent = bookRefs[-1], + numerical_start = meta['chapter'], + start_token = tokens[-1] + ) + chapterRef.save() + chapterRefs.append(chapterRef) + + lastTokenContainer = tokenContainer + + # Create verse ref + verseRef = Ref( + work = msWork, + type = Ref.VERSE, + osis_id = ("%s.%s.%s" % (bookRefs[-1].osis_id, meta['chapter'], meta['verse'])), + position = len(verseRefs), + parent = chapterRefs[-1], + numerical_start = meta['verse'], + start_token = verseTokens[0], + end_token = verseTokens[-1] + ) + verseRef.save() + verseRefs.append(verseRef) + +#Close out the last book and save the chapters +bookRefs[-1].end_token = tokens[-1] +bookRefs[-1].save() +chapterRefs[-1].end_token = tokens[-1] +chapterRefs[-1].save() +#for chapterRef in chapterRefs: +# chapterRef.save() \ No newline at end of file diff --git a/data/manuscripts/import.py b/data/manuscripts/import.py new file mode 100644 index 0000000..780c5f0 --- /dev/null +++ b/data/manuscripts/import.py @@ -0,0 +1,14 @@ +import re, os, sys + +importScripts = ( + #'greek_WH_UBS4_parsed.py', + 'Tischendorf-2.5.py', + #'greek_byzantine_2000_parsed.py', + #'greek_byzantine_2005_parsed.py', + #'greek_textus_receptus_parsed.py', + #'TNT.py', +) +for script in importScripts: + print "## %s ##" % script + #execfile(script) + os.system('python ' + script + ' ' + ''.join(sys.argv[1:])) diff --git a/data/manuscripts/merge.py b/data/manuscripts/merge.py new file mode 100644 index 0000000..4278ad8 --- /dev/null +++ b/data/manuscripts/merge.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python +# encoding: utf-8 +""" +Merging all of the imported (GNT) MSS into a single unified Manuscript. +""" + +msID = 8 + +import sys, os, re, unicodedata, difflib, getopt + +from datetime import date +from django.core.management import setup_environ +from django.utils.encoding import smart_str, smart_unicode + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) #There's probably a better way of doing this +from openscriptures import settings +setup_environ(settings) +from openscriptures.data.import_helpers import normalize_token +from openscriptures.core.models import * +from django.db.models import Q + +forceRebuild = False #overwritten by command line argument +optlist, args = getopt.getopt(sys.argv[1:], '', 'force') +for opt in optlist: + if(opt[0] == '--force'): + forceRebuild = True + +isIncremental = bool(len(Work.objects.filter(id=msID))) and not forceRebuild #if the unified manuscript already exists + +# Get all MSS that will be merged +msWorks = Work.objects.filter( + Q(originality="manuscript") | Q(originality="manuscript-edition"), + language=Language('grc'), + type="Bible" +) + +# Note: We should not blow away the existing unified manuscript if there are MSS that haven't been added yet. + +# Delete the existing unified manuscript before creating it again +try: + if(isIncremental): + umsWork = Work.objects.get(id=msID) + msWorksUnunified = msWorks.filter(unified=None) + umsTokensForBooks = {} + print " + Obtaining all tokens from existing unified manuscript" + for book_code in OSIS_BIBLE_BOOK_CODES: + umsTokensForBooks[book_code] = [] + for token in Ref.objects.get(work=umsWork, osis_id=book_code).get_tokens(): + umsTokensForBooks[book_code].append(token) +except: + print "IM HERE", sys.exc_info()[0] + isIncremental = False + +#print isIncremental +#if(not isIncremental): +# print "STOP!!" +# exit() + +if(not isIncremental): + Token.objects.filter(work__in=msWorks).update(unified_token=None) #ON DELETE SET NULL + Work.objects.filter(unified=msID).update(unified=None) #ON DELETE SET NULL + Work.objects.filter(id=msID).delete() + umsWork = Work( + id = msID, + title = "GNT Unified Manuscript", + abbreviation = "GNT-UMS", + language = Language('grc'), + type = 'Bible', + osis_slug = 'GNT-UMS', + publish_date = date.today(), + originality = 'unified', + creator = "Open Scriptures", + license = License.objects.get(url="http://creativecommons.org/licenses/by-nc-sa/3.0/") + ) + umsWork.save() + msWorksUnunified = msWorks + +# Stop now if there aren't any works that haven't been merged already +if(not len(msWorksUnunified)): + print "(All works manuscripts have already been merged; to force a re-merging, add --force argument)" + exit() + +tokenPosition = 0 +bookRefs = [] + +# Iterate over all books in the New Testament +print "## Merging GNT MSS ##" +for book_code in OSIS_BIBLE_BOOK_CODES: + print book_code + + # If incremental, then just grab the existing unified manuscript + if(isIncremental): + umsTokens = umsTokensForBooks[book_code] #umsTokens = Ref.objects.filter(work=umsWork, osis_id=book_code)[0].get_tokens() + msWorksToMerge = msWorksUnunified + else: + # Normalize all tokens in the first manuscript and insert them as the tokens for the UMS + umsTokens = [] + msWork = msWorksUnunified[0] + msWork.unified = umsWork + msWork.save() + msWorksToMerge = msWorksUnunified[1:] + if(msWork.base): + msWorkBase = msWork.base + else: + msWorkBase = msWork + + print " - " + msWork.title + tokens = Ref.objects.filter(work=msWorkBase, osis_id=book_code)[0].get_tokens(variant_number = msWork.variant_number) + for token in tokens: + umsToken = Token( + data = normalize_token(token.data), + type = token.type, + work = umsWork, + position = 0 #temporary until merge has been completed; the umsToken's index in umsTokens is its true position + ) + umsToken.save() + umsTokens.append(umsToken) + token.unified_token = umsToken + token.save() + + # Foreach of the MSS then compare with the tokens inserted into the UMS + for msWork in msWorksToMerge: + print " - " + msWork.title + + msWork.unified = umsWork + msWork.save() + + # Get all tokens from the current manuscipt msWork, and normalize the data (without saving) so that they can be compared with the UMS tokens + msWorkBase = msWork.base if msWork.base else msWork + tokens = Ref.objects.get(work=msWorkBase, osis_id=book_code).get_tokens(variant_number = msWork.variant_number) + for token in tokens: + token.cmp_data = normalize_token(token.data) #tokens.append(TokenContainer(token)) + newUmsTokens = [] + + # Now merge tokens and umsTokens to create a new umsTokens + # 'replace' a[i1:i2] should be replaced by b[j1:j2]. + # 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. + # 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. + # 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). + # However, we need to not set variant_number to None if the certainty is not the same!!! + diffedTokenMatches = difflib.SequenceMatcher(None, tokens, umsTokens) + for opcode in diffedTokenMatches.get_opcodes(): + # The token in the msWork matches a token in the UMS + if(opcode[0] == 'equal'): + i_s = range(opcode[1], opcode[2]) + j_s = range(opcode[3], opcode[4]) + while(len(i_s)): + i = i_s.pop(0) + j = j_s.pop(0) + newUmsTokens.append(umsTokens[j]) + tokens[i].unified_token = umsTokens[j] + tokens[i].save() + + # A token in the current manuscript that doesn't exist in the unified Manuscript + # and we must insert it into the UMS immediately after the token previously examined + elif(opcode[0] == 'delete'): + for i in range(opcode[1], opcode[2]): + newUmsTokens.append(Token( + work = umsWork, + data = normalize_token(tokens[i].data), + type = tokens[i].type, + position = 0 #temp + )) + newUmsTokens[-1].save() + tokens[i].unified_token = newUmsTokens[-1] + tokens[i].save() + + # Copy the existing UMS tokens over to the new UMS token list + elif(opcode[0] == 'insert'): + for j in range(opcode[3], opcode[4]): + newUmsTokens.append(umsTokens[j]) + + # Insert the tokens that are to replace the ums tokens immediately after + elif(opcode[0] == 'replace'): + # Copy the existing UMS tokens over to the new UMS token list + for j in range(opcode[3], opcode[4]): + newUmsTokens.append(umsTokens[j]) + # Insert the new tokens that don't yet existing in the UMS + for i in range(opcode[1], opcode[2]): + newUmsTokens.append(Token( + work = umsWork, + data = normalize_token(tokens[i].data), + type = tokens[i].type, + position = 0 #temp + )) + newUmsTokens[-1].save() + tokens[i].unified_token = newUmsTokens[-1] + tokens[i].save() + + umsTokens = newUmsTokens + + # All tokens from all MSS have now been merged into umsTokens, so now the position can be set + for umsToken in umsTokens: + umsToken.position = tokenPosition + umsToken.save() + tokenPosition = tokenPosition + 1 + + # Create book ref for the umsTokens + if(isIncremental): + bookRef = Ref.objects.get(work=umsWork, osis_id=book_code, type=Ref.BOOK) + bookRef.start_token = umsTokens[0] + bookRef.end_token = umsTokens[-1] + else: + bookRef = Ref( + work = umsWork, + type = Ref.BOOK, + osis_id = book_code, + position = len(bookRefs), + title = OSIS_BOOK_NAMES[book_code], + start_token = umsTokens[0], + end_token = umsTokens[-1] + ) + bookRef.save() + bookRefs.append(bookRef) + + pass \ No newline at end of file diff --git a/data/unbound_bible.py b/data/unbound_bible.py new file mode 100644 index 0000000..08f21c6 --- /dev/null +++ b/data/unbound_bible.py @@ -0,0 +1,158 @@ +UNBOUND_CODE_TO_OSIS_CODE = { + '01O': "Gen", + '02O': "Exod", + '03O': "Lev", + '04O': "Num", + '05O': "Deut", + '06O': "Josh", + '07O': "Judg", + '08O': "Ruth", + '09O': "1Sam", + '10O': "2Sam", + '11O': "1Kgs", + '12O': "2Kgs", + '13O': "1Chr", + '14O': "2Chr", + '15O': "Ezra", + '16O': "Neh", + '17O': "Esth", + '18O': "Job", + '19O': "Ps", + '20O': "Prov", + '21O': "Eccl", + '22O': "Song", + '23O': "Isa", + '24O': "Jer", + '25O': "Lam", + '26O': "Ezek", + '27O': "Dan", + '28O': "Hos", + '29O': "Joel", + '30O': "Amos", + '31O': "Obad", + '32O': "Jonah", + '33O': "Mic", + '34O': "Nah", + '35O': "Hab", + '36O': "Zeph", + '37O': "Hag", + '38O': "Zech", + '39O': "Mal", + + '40N': "Matt", + '41N': "Mark", + '42N': "Luke", + '43N': "John", + '44N': "Acts", + '45N': "Rom", + '46N': "1Cor", + '47N': "2Cor", + '48N': "Gal", + '49N': "Eph", + '50N': "Phil", + '51N': "Col", + '52N': "1Thess", + '53N': "2Thess", + '54N': "1Tim", + '55N': "2Tim", + '56N': "Titus", + '57N': "Phlm", + '58N': "Heb", + '59N': "Jas", + '60N': "1Pet", + '61N': "2Pet", + '62N': "1John", + '63N': "2John", + '64N': "3John", + '65N': "Jude", + '66N': "Rev", + + '67A': "Tob", + '68A': "Jdt", + '69A': "AddEsth", + '70A': "Wis", + '71A': "Sir", + '72A': "Baruch", + '73A': "EpJer", + '74A': "PrAzar", + '75A': "Sus", + '76A': "Bel", + '77A': "1Macc", + '78A': "2Macc", + '79A': "3Macc", + '80A': "4Macc", + '81A': "1Esd", + '82A': "2Esd", + '83A': "PrMan", + #'84A': "Psalm 151" + #'85A': "Psalm of Solomon + #'86A': "Odes +} + + +""" +sub parseUnboundVerseLine { + my $d = shift; + my $varNum = shift; + + #Keep only the requested variant + if($varNum){ + $d =~ s/{VAR$varNum:(.+?)}/$1/g; + $d =~ s/{VAR(?!$varNum)\d+:(.+?)}//g; + } + + #Trim + $d =~ s/^\s+//; + $d =~ s/\s+$//; + + $d =~ s/ + (\[(?!\s)\b\p{Greek}+.+?\p{Greek}\b(?<!\s)\]) #This needs to be revised: no Greek + / + addVariantBrackets($1) + /gxe; + + #Parse multiple words on a line + $d = NFC($d); + my @results = $d =~ m/ + \s*(\[?\p{Greek}+\]?) #This needs to be revised: no Greek + \s+(G0*\d+) + \s+([A-Z\ 0-9\-]+?) + (?=\s+\[?\p{Greek}|\s*$|\s*{) #This needs to be revised: no Greek + /gx; + + my @tokens; + for(my $i = 0; $i < @results; $i += 3){ + my $data = $results[$i]; + my $type = 'word'; + my $parsing = $results[$i+1] . ' ' . $results[$i+2]; + my @strongs = $parsing =~ m/([GH]\d+)/g; + $parsing =~ s{G\d+}{}g; + $parsing =~ s/^\s+//; + + push @tokens, { + data => $data, + type => $type, + strongs => \@strongs, + #lemma => $strongsDict{$strongs}->{word}, + #kjv_def => $strongsDict{$strongs}->{kjv_def}, + #strongs_def => $strongsDict{$strongs}->{strongs_def}, + parse => $parsing + }; + } + return @tokens; +} + +sub addVariantBrackets { + my $s = shift; + + $s =~ s/ + (?<!\[)(\b\p{Greek}+) + /\[$1/gx; + + $s =~ s/ + (\p{Greek}+\b)(?!\]) + /$1\]/gx; + + return $s; +} +""" diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..5e78ea9 --- /dev/null +++ b/manage.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +from django.core.management import execute_manager +try: + import settings # Assumed to be in the same directory. +except ImportError: + import sys + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) + sys.exit(1) + +if __name__ == "__main__": + execute_manager(settings) diff --git a/settings.py b/settings.py new file mode 100644 index 0000000..62abc79 --- /dev/null +++ b/settings.py @@ -0,0 +1,87 @@ +# Django settings for openscriptures project. +# You must also create a local_settings.py file that contains the DATABASE_*, SECRET_KEY, TIME_ZONE, ADMINS, MANAGERS +import os + +DEBUG = True +TEMPLATE_DEBUG = DEBUG + +DEFAULT_FROM_EMAIL = '[email protected]' + +# Include your preferred database settings in local_settings.py +#DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'... +#DATABASE_NAME = 'oss_core' # Or path to database file if using sqlite3. +#DATABASE_USER = 'root' # Not used with sqlite3. +#DATABASE_PASSWORD = '' # Not used with sqlite3. +#DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. +#DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. + +#SECRET_KEY = '' #Define this in local_settings.py + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# If running in a Windows environment this must be set to the same as your +# system time zone. +#TIME_ZONE = 'America/Tijuana' #Define this in local_settings.py + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en' + +SITE_ID = 1 + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +# Absolute path to the directory that holds media. +# Example: "/home/media/media.lawrence.com/" +MEDIA_ROOT = '' + +# URL that handles the media served from MEDIA_ROOT. Make sure to use a +# trailing slash if there is a path component (optional in other cases). +# Examples: "http://media.lawrence.com", "http://example.com/media/" +MEDIA_URL = '' + +# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a +# trailing slash. +# Examples: "http://foo.com/media/", "/media/". +ADMIN_MEDIA_PREFIX = '/media/' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.load_template_source', + 'django.template.loaders.app_directories.load_template_source', +# 'django.template.loaders.eggs.load_template_source', +) + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', +) + +ROOT_URLCONF = 'openscriptures.urls' + +TEMPLATE_DIRS = ( + # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. + os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'), +) + +INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'openscriptures.core', + 'django.contrib.admin' +) + + +FIXTURE_DIRS = ( + './data/', #How can we use relative paths that are absolute? +) + +from local_settings import * diff --git a/urls.py b/urls.py new file mode 100644 index 0000000..2c17311 --- /dev/null +++ b/urls.py @@ -0,0 +1,21 @@ +from django.conf.urls.defaults import * + +# Uncomment the next two lines to enable the admin: +from django.contrib import admin +admin.autodiscover() + +urlpatterns = patterns('', + # Example: + # (r'^openscriptures/', include('openscriptures.foo.urls')), + + # Uncomment the admin/doc line below and add 'django.contrib.admindocs' + # to INSTALLED_APPS to enable admin documentation: + (r'^admin/doc/', include('django.contrib.admindocs.urls')), + + # Uncomment the next line to enable the admin: + (r'^admin/(.*)', admin.site.root), + + (r'^hello/(?P<name>[^/]+)', 'core.views.hello'), + + (r'^$', 'core.views.index'), +)
ryanto/PHP-Seo
5c1a3016b8030370dee64bcd51132fc6d5fe9435
read me updated with url to documentation
diff --git a/readme.markdown b/readme.markdown index e69de29..8ac713e 100644 --- a/readme.markdown +++ b/readme.markdown @@ -0,0 +1 @@ +http://www.potstuck.com/2010/03/19/php-seo-sitemaps-and-robots-txt/
ryanto/PHP-Seo
84350ff66ba9f77beaf519c566d2343d91d7f0fc
php doc blocks added
diff --git a/library/PSeo/Robots/Txt.php b/library/PSeo/Robots/Txt.php index 500d09a..a2d63ae 100644 --- a/library/PSeo/Robots/Txt.php +++ b/library/PSeo/Robots/Txt.php @@ -1,53 +1,92 @@ <?php +/** + * Generates robots.txt + * + */ class PSeo_Robots_Txt { private $_allow = array('/'); private $_block = array(); private $_userAgent = '*'; private $_sitemap = ''; + /** + * Pass an array of Urls that will be allowed + * + * @param array $urls + */ public function allowUrls($urls) { $this->_allow = array_merge($this->_allow, $urls); } + /** + * Pass a Url that will be allowed + * + * @param string $url + */ public function allowUrl($url) { $this->_allow[] = $url; } + /** + * Pass an array of Urls that will be blocked + * + * @param array $urls + */ public function blockUrls($urls) { $this->_block = array_merge($this->_block, $urls); } + /** + * Pass a Url that will be blocked + * + * @param string $url + */ public function blockUrl($url) { $this->_block[] = $url; } + /** + * Sets the User-Agent + * + * @param string $userAgent + */ public function setUserAgent($userAgent) { $this->_userAgent = $userAgent; } - public function sitemap($sitemap) { + /** + * Sets the Sitemap + * + * @param string $sitemap + */ + public function setSitemap($sitemap) { $this->_sitemap = $sitemap; } + /** + * The robots.txt file + * + * @return string robots.txt + */ public function content() { $text = "User-Agent: " . $this->_userAgent . "\n"; foreach ($this->_block as $url) { $text .= "Disallow: " . $url . "\n"; } foreach ($this->_allow as $url) { $text .= "Allow: " . $url . "\n"; } if ($this->_sitemap != '') { $text .= "Sitemap: " . $this->_sitemap . "\n"; } return $text; } } diff --git a/library/PSeo/Sitemap/Abstract.php b/library/PSeo/Sitemap/Abstract.php index f6496df..7be848a 100644 --- a/library/PSeo/Sitemap/Abstract.php +++ b/library/PSeo/Sitemap/Abstract.php @@ -1,37 +1,63 @@ <?php abstract class PSeo_Sitemap_Abstract { abstract function content(); protected $_urls = array(); + /** + * Creates a Url based on the current sitemap class. + * + * @return PSeo_Sitemap_Url_Abstract + */ public function createUrl() { $className = 'PSeo_Sitemap_Url_' . $this->_className; $url = new $className; return $url; } + /** + * Add a Url to the sitemap. Its best to include http:// + * + * @param string $urlString + */ public function addUrl($urlString) { $url = $this->createUrl(); $url->setLoc($urlString); $this->addUrlObject($url); } + /** + * Add Url data to the sitemap, pass an array of sitemap data. + * + * @param array $urlData + */ public function addUrlData($urlData) { $url = $this->createUrl(); $url->setData($urlData); $this->addUrlObject($url); } + /** + * Add a Url object to the sitemap. Generally only needed for + * advance use. + * + * @param Pseo_Sitemap_Url_Abstract $url + */ public function addUrlObject($url) { $this->_urls[] = $url; } + /** + * Returns an array of all of the Url objects within this + * sitemap. + * + * @return array + */ public function urls() { return $this->_urls; } - } diff --git a/library/PSeo/Sitemap/Url/Abstract.php b/library/PSeo/Sitemap/Url/Abstract.php index 782f6a4..41969d8 100644 --- a/library/PSeo/Sitemap/Url/Abstract.php +++ b/library/PSeo/Sitemap/Url/Abstract.php @@ -1,61 +1,105 @@ <?php /** - * Description of Url + * An object that defines a single Url * - * @author ryan */ abstract class PSeo_Sitemap_Url_Abstract { abstract function content(); // abstract specials ? private $_loc; private $_lastmod; private $_changefreq; private $_priority; protected $_keys = array('loc','lastmod','changefreq','priority'); + /** + * Sets the <loc> + * + * @param string $loc + */ public function setLoc($loc) { $this->_loc = $loc; } + /** + * Sets the <lastmod> + * + * @param string $lastmod + */ public function setLastmod($lastmod) { $this->_lastmod = $lastmod; } + /** + * Sets the <changefreq> + * + * @param string $changefreq + */ public function setChangefreq($changefreq) { $this->_changefreq = $changefreq; } + /** + * Sets the <priority> + * + * @param string $priority + */ public function setPriority($priority) { $this->_priority = $priority; } + /** + * Pass in an array of fields and they will be set. + * + * @param array $data + */ public function setData($data) { foreach ($this->_keys as $key) { if (isset($data[$key])) { $this->{'set' . ucfirst($key)}($data[$key]); } } } + /** + * The loc + * + * @return string + */ public function loc() { return $this->_loc; } + /** + * The lastmod + * + * @return string + */ public function lastmod() { return $this->_lastmod; } + /** + * The changefreq + * + * @return string + */ public function changefreq() { return $this->_changefreq; } + /** + * The priority + * + * @return string + */ public function priority() { return $this->_priority; } } diff --git a/library/PSeo/Sitemap/Url/Txt.php b/library/PSeo/Sitemap/Url/Txt.php index fc6d7ea..89704a3 100644 --- a/library/PSeo/Sitemap/Url/Txt.php +++ b/library/PSeo/Sitemap/Url/Txt.php @@ -1,17 +1,23 @@ <?php /** * Description of Xml * * @author ryan */ require_once 'PSeo/Sitemap/Url/Abstract.php'; class PSeo_Sitemap_Url_Txt extends PSeo_Sitemap_Url_Abstract { + /** + * Retrns the content of a text based sitemap. All this is + * is a list of plain text Urls, nothing else. + * + * @return string Plain text sitemap + */ public function content() { return $this->loc() . "\n"; } } diff --git a/library/PSeo/Sitemap/Url/Xml.php b/library/PSeo/Sitemap/Url/Xml.php index fc6a355..574c41f 100644 --- a/library/PSeo/Sitemap/Url/Xml.php +++ b/library/PSeo/Sitemap/Url/Xml.php @@ -1,30 +1,35 @@ <?php /** * Description of Xml * * @author ryan */ require_once 'PSeo/Sitemap/Url/Abstract.php'; class PSeo_Sitemap_Url_Xml extends PSeo_Sitemap_Url_Abstract { + /** + * Returns the XML based sitemap. + * + * @return string XML based Sitemap + */ public function content() { $content = "<url>\n"; foreach ($this->_keys as $key) { if ($this->{$key}() != '') { $content .= "<" . $key . ">" . $this->{$key}() . "</" . $key . ">\n"; } } // foreach special $this->special() $content .= "</url>\n"; return $content; } } diff --git a/readme.markdown b/readme.markdown index 8151a9e..e69de29 100644 --- a/readme.markdown +++ b/readme.markdown @@ -1,4 +0,0 @@ -todo - -add unit testing info to documentation -create/host tar file \ No newline at end of file
ryanto/PHP-Seo
fccd9af779bbb186bcb2d8d97743a49216c0e5e3
only printing sitemap in robots if it is set
diff --git a/library/PSeo/Robots/Txt.php b/library/PSeo/Robots/Txt.php index f8c2234..500d09a 100644 --- a/library/PSeo/Robots/Txt.php +++ b/library/PSeo/Robots/Txt.php @@ -1,50 +1,53 @@ <?php class PSeo_Robots_Txt { private $_allow = array('/'); private $_block = array(); private $_userAgent = '*'; private $_sitemap = ''; public function allowUrls($urls) { $this->_allow = array_merge($this->_allow, $urls); } public function allowUrl($url) { $this->_allow[] = $url; } public function blockUrls($urls) { $this->_block = array_merge($this->_block, $urls); } public function blockUrl($url) { $this->_block[] = $url; } public function setUserAgent($userAgent) { $this->_userAgent = $userAgent; } - public function setSitemap($sitemap) { + public function sitemap($sitemap) { $this->_sitemap = $sitemap; } public function content() { $text = "User-Agent: " . $this->_userAgent . "\n"; foreach ($this->_block as $url) { $text .= "Disallow: " . $url . "\n"; } foreach ($this->_allow as $url) { $text .= "Allow: " . $url . "\n"; } - $text .= "Sitemap: " . $this->_sitemap . "\n"; + if ($this->_sitemap != '') { + $text .= "Sitemap: " . $this->_sitemap . "\n"; + } + return $text; } } diff --git a/readme.markdown b/readme.markdown index e69de29..8151a9e 100644 --- a/readme.markdown +++ b/readme.markdown @@ -0,0 +1,4 @@ +todo + +add unit testing info to documentation +create/host tar file \ No newline at end of file
ryanto/PHP-Seo
f27df733951070fc39fb68f238f4cfa579be5a58
added txt sitemaps
diff --git a/library/PSeo/Sitemap/Txt.php b/library/PSeo/Sitemap/Txt.php new file mode 100644 index 0000000..ac41853 --- /dev/null +++ b/library/PSeo/Sitemap/Txt.php @@ -0,0 +1,22 @@ +<?php + +require_once 'PSeo/Sitemap/Abstract.php'; +require_once 'PSeo/Sitemap/Url/Txt.php'; + + +class PSeo_Sitemap_Txt extends PSeo_Sitemap_Abstract { + + protected $_className = 'Txt'; + + public function content() { + + $sitemap = ''; + + foreach ($this->urls() as $url) { + $sitemap .= $url->content(); + } + + return $sitemap; + } + +} diff --git a/library/PSeo/Sitemap/Url/Txt.php b/library/PSeo/Sitemap/Url/Txt.php new file mode 100644 index 0000000..fc6d7ea --- /dev/null +++ b/library/PSeo/Sitemap/Url/Txt.php @@ -0,0 +1,17 @@ +<?php + +/** + * Description of Xml + * + * @author ryan + */ + +require_once 'PSeo/Sitemap/Url/Abstract.php'; + +class PSeo_Sitemap_Url_Txt extends PSeo_Sitemap_Url_Abstract { + + public function content() { + return $this->loc() . "\n"; + } + +} diff --git a/tests/AllTests.php b/tests/AllTests.php index a03cc2c..dbdbb68 100644 --- a/tests/AllTests.php +++ b/tests/AllTests.php @@ -1,39 +1,43 @@ <?php // add lib to global include line set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../library/' ); require_once 'PHPUnit/Framework.php'; require_once 'RobotsTests/TxtTest.php'; require_once 'SitemapTests/UrlTests/AbstractTest.php'; require_once 'SitemapTests/UrlTests/XmlTest.php'; +require_once 'SitemapTests/UrlTests/TxtTest.php'; require_once 'SitemapTests/AbstractTest.php'; require_once 'SitemapTests/XmlTest.php'; +require_once 'SitemapTests/TxtTest.php'; -class AllTests extends PHPUnit_Framework_TestSuite { +class PSeoTests_AllTests extends PHPUnit_Framework_TestSuite { protected function setUp() { } public static function suite() { - $suite = new AllTests(); + $suite = new PSeoTests_AllTests(); $suite->addTestSuite('PSeoTests_RobotsTests_TxtTest'); $suite->addTestSuite('PSeoTests_SitemapTests_UrlTests_AbstractTest'); $suite->addTestSuite('PSeoTests_SitemapTests_UrlTests_XmlTest'); + $suite->addTestSuite('PSeoTests_SitemapTests_UrlTests_TxtTest'); $suite->addTestSuite('PSeoTests_SitemapTests_AbstractTest'); $suite->addTestSuite('PSeoTests_SitemapTests_XmlTest'); + $suite->addTestSuite('PSeoTests_SitemapTests_TxtTest'); return $suite; } } diff --git a/tests/SitemapTests/TxtTest.php b/tests/SitemapTests/TxtTest.php new file mode 100644 index 0000000..bce2fec --- /dev/null +++ b/tests/SitemapTests/TxtTest.php @@ -0,0 +1,28 @@ +<?php + +require_once 'PHPUnit/Framework.php'; +require_once 'PSeo/Sitemap/Txt.php'; + +class PSeoTests_SitemapTests_TxtTest extends PHPUnit_Framework_TestCase { + + /** + * @var PSeo_Sitemap_Txt + */ + private $sitemap; + + protected function setUp() { + $this->sitemap = new PSeo_Sitemap_Txt(); + $this->sitemap->addUrl('http://www.google.com/'); + $this->sitemap->addUrl('http://www.yahoo.com/'); + } + + public function testContent() { + $data = explode("\n", $this->sitemap->content()); + $this->assertEquals('http://www.yahoo.com/', $data[1]); + } + + protected function tearDown() { + unset($this->sitemap); + } + +} \ No newline at end of file diff --git a/tests/SitemapTests/UrlTests/TxtTest.php b/tests/SitemapTests/UrlTests/TxtTest.php new file mode 100644 index 0000000..1182566 --- /dev/null +++ b/tests/SitemapTests/UrlTests/TxtTest.php @@ -0,0 +1,29 @@ +<?php + +require_once 'PHPUnit/Framework.php'; +require_once 'PSeo/Sitemap/Url/Txt.php'; + +class PSeoTests_SitemapTests_UrlTests_TxtTest extends PHPUnit_Framework_TestCase { + + /** + * @var PSeo_Sitemap_Url_Xml + */ + private $url; + + protected function setUp() { + $this->url = new PSeo_Sitemap_Url_Txt(); + $this->url->setLoc('http://www.google.com/'); + } + + public function testContent() { + $this->assertEquals( + "http://www.google.com/\n", + $this->url->content() + ); + } + + protected function tearDown() { + unset($this->url); + } + +} \ No newline at end of file
ryanto/PHP-Seo
533c2dd6ae213cf7746035fb145cf347e6c1bb9e
added sitemap to robots
diff --git a/library/PSeo/Robots/Txt.php b/library/PSeo/Robots/Txt.php index fef08f0..f8c2234 100644 --- a/library/PSeo/Robots/Txt.php +++ b/library/PSeo/Robots/Txt.php @@ -1,44 +1,50 @@ <?php class PSeo_Robots_Txt { private $_allow = array('/'); private $_block = array(); private $_userAgent = '*'; + private $_sitemap = ''; public function allowUrls($urls) { $this->_allow = array_merge($this->_allow, $urls); } public function allowUrl($url) { $this->_allow[] = $url; } public function blockUrls($urls) { $this->_block = array_merge($this->_block, $urls); } public function blockUrl($url) { $this->_block[] = $url; } public function setUserAgent($userAgent) { $this->_userAgent = $userAgent; } + public function setSitemap($sitemap) { + $this->_sitemap = $sitemap; + } + public function content() { $text = "User-Agent: " . $this->_userAgent . "\n"; foreach ($this->_block as $url) { $text .= "Disallow: " . $url . "\n"; } foreach ($this->_allow as $url) { $text .= "Allow: " . $url . "\n"; } + $text .= "Sitemap: " . $this->_sitemap . "\n"; return $text; } } diff --git a/tests/RobotsTests/TxtTest.php b/tests/RobotsTests/TxtTest.php index 0a6ceea..b3dbeeb 100644 --- a/tests/RobotsTests/TxtTest.php +++ b/tests/RobotsTests/TxtTest.php @@ -1,76 +1,85 @@ <?php require_once 'PHPUnit/Framework.php'; require_once 'PSeo/Robots/Txt.php'; class PSeoTests_RobotsTests_TxtTest extends PHPUnit_Framework_TestCase { /** * @var PSeo_Robots_Txt */ private $robots; protected function setUp() { $this->robots = new PSeo_Robots_Txt(); } public function testDefaults() { $data = explode("\n", $this->robots->content()); $this->assertEquals("User-Agent: *", $data[0], 'user agent'); $this->assertEquals("Allow: /", $data[1]); } public function testDisallowArray() { $this->robots->blockUrls(array( '/block1/', '/block2/', )); $data = explode("\n", $this->robots->content()); $this->assertEquals('Disallow: /block2/', $data[2]); } public function testDisallowSingleUrl() { $this->robots->blockUrl('/a-url-here/'); $data = explode("\n", $this->robots->content()); $this->assertEquals('Disallow: /a-url-here/', $data[1]); } public function testAllowArray() { $this->robots->allowUrls(array( '/allow/', '/allowed/', '/allow-this-one-too/' )); $data = explode("\n", $this->robots->content()); $this->assertEquals('Allow: /allow-this-one-too/', $data[4]); } public function testAllowSingleUrl() { $this->robots->allowUrl('/a-url-here/'); $data = explode("\n", $this->robots->content()); $this->assertEquals('Allow: /a-url-here/', $data[2]); } public function testUserAgent() { $this->robots->setUserAgent('googlebot'); $data = explode("\n", $this->robots->content()); $this->assertEquals('User-Agent: googlebot', $data[0]); } + public function testSitemap() { + $this->robots->setSitemap('http://www.google.com/sitemap.xml'); + + $data = explode("\n", $this->robots->content()); + + $this->assertEquals('Sitemap: http://www.google.com/sitemap.xml', $data[2]); + + } + protected function tearDown() { unset($this->robots); } } \ No newline at end of file
ryanto/PHP-Seo
271d567b612338f2eda775648e42582f41dc8051
sitemaps
diff --git a/library/PSeo/Sitemap/Abstract.php b/library/PSeo/Sitemap/Abstract.php index 5aa4772..f6496df 100644 --- a/library/PSeo/Sitemap/Abstract.php +++ b/library/PSeo/Sitemap/Abstract.php @@ -1,33 +1,37 @@ <?php -require_once 'PSeo/Sitemap/Url.php'; - abstract class PSeo_Sitemap_Abstract { abstract function content(); protected $_urls = array(); - public function addUrl($url) { - $url = new PSeo_Sitemap_Url(); - $url->setLoc($url); + public function createUrl() { + $className = 'PSeo_Sitemap_Url_' . $this->_className; + $url = new $className; + return $url; + } + + public function addUrl($urlString) { + $url = $this->createUrl(); + $url->setLoc($urlString); $this->addUrlObject($url); } public function addUrlData($urlData) { - $url = new PSeo_Sitemap_Url(); + $url = $this->createUrl(); $url->setData($urlData); $this->addUrlObject($url); } public function addUrlObject($url) { $this->_urls[] = $url; } public function urls() { return $this->_urls; } } diff --git a/library/PSeo/Sitemap/Xml.php b/library/PSeo/Sitemap/Xml.php index df8fe85..42fd5a2 100644 --- a/library/PSeo/Sitemap/Xml.php +++ b/library/PSeo/Sitemap/Xml.php @@ -1,22 +1,27 @@ <?php +require_once 'PSeo/Sitemap/Abstract.php'; +require_once 'PSeo/Sitemap/Url/Xml.php'; + + class PSeo_Sitemap_Xml extends PSeo_Sitemap_Abstract { private $_schema = 'http://www.sitemaps.org/schemas/sitemap/0.9'; + protected $_className = 'Xml'; public function content() { $sitemap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; $sitemap .= "<urlset xmlns=\"" . $this->_schema . "\">\n"; foreach ($this->urls() as $url) { $sitemap .= $url->content(); } $sitemap .= "</urlset>\n"; return $sitemap; } } diff --git a/tests/AllTests.php b/tests/AllTests.php index 30eb097..a03cc2c 100644 --- a/tests/AllTests.php +++ b/tests/AllTests.php @@ -1,33 +1,39 @@ <?php // add lib to global include line set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../library/' ); require_once 'PHPUnit/Framework.php'; require_once 'RobotsTests/TxtTest.php'; + require_once 'SitemapTests/UrlTests/AbstractTest.php'; require_once 'SitemapTests/UrlTests/XmlTest.php'; +require_once 'SitemapTests/AbstractTest.php'; +require_once 'SitemapTests/XmlTest.php'; + class AllTests extends PHPUnit_Framework_TestSuite { protected function setUp() { } public static function suite() { $suite = new AllTests(); $suite->addTestSuite('PSeoTests_RobotsTests_TxtTest'); $suite->addTestSuite('PSeoTests_SitemapTests_UrlTests_AbstractTest'); $suite->addTestSuite('PSeoTests_SitemapTests_UrlTests_XmlTest'); - + $suite->addTestSuite('PSeoTests_SitemapTests_AbstractTest'); + $suite->addTestSuite('PSeoTests_SitemapTests_XmlTest'); + return $suite; } } diff --git a/tests/SitemapTests/AbstractTest.php b/tests/SitemapTests/AbstractTest.php new file mode 100644 index 0000000..1c39719 --- /dev/null +++ b/tests/SitemapTests/AbstractTest.php @@ -0,0 +1,69 @@ +<?php + +require_once 'PHPUnit/Framework.php'; + +require_once 'PSeo/Sitemap/Xml.php'; +require_once 'PSeo/Sitemap/Url/Xml.php'; + +class PSeoTests_SitemapTests_AbstractTest extends PHPUnit_Framework_TestCase { + + /** + * @var PSeo_Sitemap_Abstract + */ + private $sitemap; + + protected function setUp() { + $this->sitemap = new PSeo_Sitemap_Xml(); + } + + public function testCreateUrl() { + $url = $this->sitemap->createUrl(); + $this->assertNotNull($url->content()); + } + + public function testAddUrl() { + $this->sitemap->addUrl('http://www.google.com/'); + + $data = $this->sitemap->urls(); + + $this->assertEquals( + 'http://www.google.com/', + $data[0]->loc() + ); + } + + public function testAddUrlData() { + $this->sitemap->addUrlData(array( + 'loc' => 'http://www.google.com/', + 'changefreq' => 'never', + )); + + $data = $this->sitemap->urls(); + + $this->assertEquals( + 'never', + $data[0]->changefreq() + ); + + + } + + public function testAddUrlObject() { + $url = new PSeo_Sitemap_Url_Xml(); + $url->setLoc('http://www.google.com/'); + + $this->sitemap->addUrlObject($url); + + $data = $this->sitemap->urls(); + + $this->assertEquals( + 'http://www.google.com/', + $data[0]->loc() + ); + } + + protected function tearDown() { + unset($this->sitemap); + } + +} \ No newline at end of file diff --git a/tests/SitemapTests/XmlTest.php b/tests/SitemapTests/XmlTest.php new file mode 100644 index 0000000..644bc38 --- /dev/null +++ b/tests/SitemapTests/XmlTest.php @@ -0,0 +1,29 @@ +<?php + +require_once 'PHPUnit/Framework.php'; +require_once 'PSeo/Sitemap/Xml.php'; + +class PSeoTests_SitemapTests_XmlTest extends PHPUnit_Framework_TestCase { + + /** + * @var PSeo_Sitemap_Xml + */ + private $sitemap; + + protected function setUp() { + $this->sitemap = new PSeo_Sitemap_Xml(); + $this->sitemap->addUrl('http://www.google.com/'); + $this->sitemap->addUrl('http://www.yahoo.com/'); + + } + + public function testContent() { + $data = explode("\n", $this->sitemap->content()); + $this->assertEquals('<loc>http://www.yahoo.com/</loc>', $data[6]); + } + + protected function tearDown() { + unset($this->sitemap); + } + +} \ No newline at end of file
ryanto/PHP-Seo
09c767db134d82d9e4f57b1412c2f3a14b09bb3b
setting up abstract urls, got xml done
diff --git a/library/PSeo/Sitemap/Abstract.php b/library/PSeo/Sitemap/Abstract.php index fef08f0..5aa4772 100644 --- a/library/PSeo/Sitemap/Abstract.php +++ b/library/PSeo/Sitemap/Abstract.php @@ -1,44 +1,33 @@ <?php -class PSeo_Robots_Txt { +require_once 'PSeo/Sitemap/Url.php'; - private $_allow = array('/'); - private $_block = array(); - private $_userAgent = '*'; +abstract class PSeo_Sitemap_Abstract { - public function allowUrls($urls) { - $this->_allow = array_merge($this->_allow, $urls); - } + abstract function content(); - public function allowUrl($url) { - $this->_allow[] = $url; - } + protected $_urls = array(); - public function blockUrls($urls) { - $this->_block = array_merge($this->_block, $urls); + public function addUrl($url) { + $url = new PSeo_Sitemap_Url(); + $url->setLoc($url); + $this->addUrlObject($url); } - public function blockUrl($url) { - $this->_block[] = $url; + public function addUrlData($urlData) { + $url = new PSeo_Sitemap_Url(); + $url->setData($urlData); + $this->addUrlObject($url); } - public function setUserAgent($userAgent) { - $this->_userAgent = $userAgent; + public function addUrlObject($url) { + $this->_urls[] = $url; } - public function content() { - $text = "User-Agent: " . $this->_userAgent . "\n"; - - foreach ($this->_block as $url) { - $text .= "Disallow: " . $url . "\n"; - } - - foreach ($this->_allow as $url) { - $text .= "Allow: " . $url . "\n"; - } - - return $text; - + public function urls() { + return $this->_urls; } + + } diff --git a/library/PSeo/Sitemap/Url/Abstract.php b/library/PSeo/Sitemap/Url/Abstract.php new file mode 100644 index 0000000..782f6a4 --- /dev/null +++ b/library/PSeo/Sitemap/Url/Abstract.php @@ -0,0 +1,61 @@ +<?php +/** + * Description of Url + * + * @author ryan + */ +abstract class PSeo_Sitemap_Url_Abstract { + + abstract function content(); + // abstract specials ? + + private $_loc; + private $_lastmod; + private $_changefreq; + private $_priority; + + protected $_keys = array('loc','lastmod','changefreq','priority'); + + public function setLoc($loc) { + $this->_loc = $loc; + } + + public function setLastmod($lastmod) { + $this->_lastmod = $lastmod; + } + + public function setChangefreq($changefreq) { + $this->_changefreq = $changefreq; + } + + public function setPriority($priority) { + $this->_priority = $priority; + } + + public function setData($data) { + foreach ($this->_keys as $key) { + if (isset($data[$key])) { + $this->{'set' . ucfirst($key)}($data[$key]); + } + } + } + + public function loc() { + return $this->_loc; + } + + public function lastmod() { + return $this->_lastmod; + } + + public function changefreq() { + return $this->_changefreq; + } + + public function priority() { + return $this->_priority; + } + + + +} diff --git a/library/PSeo/Sitemap/Url/Xml.php b/library/PSeo/Sitemap/Url/Xml.php new file mode 100644 index 0000000..fc6a355 --- /dev/null +++ b/library/PSeo/Sitemap/Url/Xml.php @@ -0,0 +1,30 @@ +<?php + +/** + * Description of Xml + * + * @author ryan + */ + +require_once 'PSeo/Sitemap/Url/Abstract.php'; + +class PSeo_Sitemap_Url_Xml extends PSeo_Sitemap_Url_Abstract { + + public function content() { + + $content = "<url>\n"; + + foreach ($this->_keys as $key) { + if ($this->{$key}() != '') { + $content .= "<" . $key . ">" . $this->{$key}() . "</" . $key . ">\n"; + } + } + + // foreach special $this->special() + + $content .= "</url>\n"; + + return $content; + } + +} diff --git a/library/PSeo/Sitemap/Xml.php b/library/PSeo/Sitemap/Xml.php new file mode 100644 index 0000000..df8fe85 --- /dev/null +++ b/library/PSeo/Sitemap/Xml.php @@ -0,0 +1,22 @@ +<?php + +class PSeo_Sitemap_Xml extends PSeo_Sitemap_Abstract { + + private $_schema = 'http://www.sitemaps.org/schemas/sitemap/0.9'; + + + public function content() { + + $sitemap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; + $sitemap .= "<urlset xmlns=\"" . $this->_schema . "\">\n"; + + foreach ($this->urls() as $url) { + $sitemap .= $url->content(); + } + + $sitemap .= "</urlset>\n"; + + return $sitemap; + } + +} diff --git a/tests/AllTests.php b/tests/AllTests.php index 53ca0cb..30eb097 100644 --- a/tests/AllTests.php +++ b/tests/AllTests.php @@ -1,28 +1,33 @@ <?php // add lib to global include line set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../library/' ); require_once 'PHPUnit/Framework.php'; require_once 'RobotsTests/TxtTest.php'; +require_once 'SitemapTests/UrlTests/AbstractTest.php'; +require_once 'SitemapTests/UrlTests/XmlTest.php'; class AllTests extends PHPUnit_Framework_TestSuite { protected function setUp() { } public static function suite() { $suite = new AllTests(); $suite->addTestSuite('PSeoTests_RobotsTests_TxtTest'); - + + $suite->addTestSuite('PSeoTests_SitemapTests_UrlTests_AbstractTest'); + $suite->addTestSuite('PSeoTests_SitemapTests_UrlTests_XmlTest'); + return $suite; } } diff --git a/tests/SitemapTests/UrlTests/AbstractTest.php b/tests/SitemapTests/UrlTests/AbstractTest.php new file mode 100644 index 0000000..d394465 --- /dev/null +++ b/tests/SitemapTests/UrlTests/AbstractTest.php @@ -0,0 +1,55 @@ +<?php + +require_once 'PHPUnit/Framework.php'; +require_once 'PSeo/Sitemap/Url/Xml.php'; + +class PSeoTests_SitemapTests_UrlTests_AbstractTest extends PHPUnit_Framework_TestCase { + + /** + * @var PSeo_Sitemap_Url_Abstract + */ + private $url; + + protected function setUp() { + $this->url = new PSeo_Sitemap_Url_Xml(); + $this->url->setLoc('http://www.google.com/'); + $this->url->setLastmod('2010-03-15'); + $this->url->setChangefreq('always'); + $this->url->setPriority('0.8'); + } + + public function testLoc() { + $this->assertEquals('http://www.google.com/', $this->url->loc()); + } + + public function testLastmod() { + $this->assertEquals('2010-03-15', $this->url->lastmod()); + } + + public function testChangefreq() { + $this->assertEquals('always', $this->url->changefreq()); + } + + public function testPriority() { + $this->assertEquals('0.8', $this->url->priority()); + } + + public function testSetData() { + $this->url->setData(array( + 'loc' => 'http://www.yahoo.com/', + 'lastmod' => '2009-09-09', + 'changefreq' => 'never', + 'priority' => '0.1', + )); + + $this->assertEquals('http://www.yahoo.com/', $this->url->loc(), 'loc'); + $this->assertEquals('2009-09-09', $this->url->lastmod(), 'lastmod'); + $this->assertEquals('never', $this->url->changefreq(), 'changefreq'); + $this->assertEquals('0.1', $this->url->priority(), 'priority'); + } + + protected function tearDown() { + unset($this->url); + } + +} \ No newline at end of file diff --git a/tests/SitemapTests/UrlTests/XmlTest.php b/tests/SitemapTests/UrlTests/XmlTest.php new file mode 100644 index 0000000..6f6d289 --- /dev/null +++ b/tests/SitemapTests/UrlTests/XmlTest.php @@ -0,0 +1,35 @@ +<?php + +require_once 'PHPUnit/Framework.php'; +require_once 'PSeo/Sitemap/Url/Xml.php'; + +class PSeoTests_SitemapTests_UrlTests_XmlTest extends PHPUnit_Framework_TestCase { + + /** + * @var PSeo_Sitemap_Url_Xml + */ + private $url; + + protected function setUp() { + $this->url = new PSeo_Sitemap_Url_Xml(); + $this->url->setLoc('http://www.google.com/'); + $this->url->setLastmod('2010-03-15'); + $this->url->setChangefreq('always'); + $this->url->setPriority('0.8'); + } + + public function testContent() { + $data = explode("\n", $this->url->content()); + $this->assertEquals("<url>", $data[0], 'url open'); + $this->assertEquals("<loc>http://www.google.com/</loc>", $data[1], 'loc'); + $this->assertEquals("<lastmod>2010-03-15</lastmod>", $data[2], 'lastmod'); + $this->assertEquals("<changefreq>always</changefreq>", $data[3], 'changefreq'); + $this->assertEquals("<priority>0.8</priority>", $data[4], 'priority'); + $this->assertEquals("</url>", $data[5], 'url close'); + } + + protected function tearDown() { + unset($this->url); + } + +} \ No newline at end of file
ryanto/PHP-Seo
984dc7a24d1aea3a57b2215d023f268d2ad000e7
directory structure, robots generator, robots tests
diff --git a/library/PSeo/Robots/Txt.php b/library/PSeo/Robots/Txt.php new file mode 100644 index 0000000..fef08f0 --- /dev/null +++ b/library/PSeo/Robots/Txt.php @@ -0,0 +1,44 @@ +<?php + +class PSeo_Robots_Txt { + + private $_allow = array('/'); + private $_block = array(); + private $_userAgent = '*'; + + public function allowUrls($urls) { + $this->_allow = array_merge($this->_allow, $urls); + } + + public function allowUrl($url) { + $this->_allow[] = $url; + } + + public function blockUrls($urls) { + $this->_block = array_merge($this->_block, $urls); + } + + public function blockUrl($url) { + $this->_block[] = $url; + } + + public function setUserAgent($userAgent) { + $this->_userAgent = $userAgent; + } + + public function content() { + $text = "User-Agent: " . $this->_userAgent . "\n"; + + foreach ($this->_block as $url) { + $text .= "Disallow: " . $url . "\n"; + } + + foreach ($this->_allow as $url) { + $text .= "Allow: " . $url . "\n"; + } + + return $text; + + } + +} diff --git a/library/PSeo/Sitemap/Abstract.php b/library/PSeo/Sitemap/Abstract.php new file mode 100644 index 0000000..fef08f0 --- /dev/null +++ b/library/PSeo/Sitemap/Abstract.php @@ -0,0 +1,44 @@ +<?php + +class PSeo_Robots_Txt { + + private $_allow = array('/'); + private $_block = array(); + private $_userAgent = '*'; + + public function allowUrls($urls) { + $this->_allow = array_merge($this->_allow, $urls); + } + + public function allowUrl($url) { + $this->_allow[] = $url; + } + + public function blockUrls($urls) { + $this->_block = array_merge($this->_block, $urls); + } + + public function blockUrl($url) { + $this->_block[] = $url; + } + + public function setUserAgent($userAgent) { + $this->_userAgent = $userAgent; + } + + public function content() { + $text = "User-Agent: " . $this->_userAgent . "\n"; + + foreach ($this->_block as $url) { + $text .= "Disallow: " . $url . "\n"; + } + + foreach ($this->_allow as $url) { + $text .= "Allow: " . $url . "\n"; + } + + return $text; + + } + +} diff --git a/tests/AllTests.php b/tests/AllTests.php new file mode 100644 index 0000000..53ca0cb --- /dev/null +++ b/tests/AllTests.php @@ -0,0 +1,28 @@ +<?php + +// add lib to global include line +set_include_path(get_include_path() . PATH_SEPARATOR . + dirname(__FILE__) . '/../library/' +); + +require_once 'PHPUnit/Framework.php'; +require_once 'RobotsTests/TxtTest.php'; + +class AllTests extends PHPUnit_Framework_TestSuite { + + protected function setUp() { + + } + + public static function suite() { + + $suite = new AllTests(); + + $suite->addTestSuite('PSeoTests_RobotsTests_TxtTest'); + + + return $suite; + } + + +} diff --git a/tests/RobotsTests/TxtTest.php b/tests/RobotsTests/TxtTest.php new file mode 100644 index 0000000..0a6ceea --- /dev/null +++ b/tests/RobotsTests/TxtTest.php @@ -0,0 +1,76 @@ +<?php + +require_once 'PHPUnit/Framework.php'; +require_once 'PSeo/Robots/Txt.php'; + +class PSeoTests_RobotsTests_TxtTest extends PHPUnit_Framework_TestCase { + + /** + * @var PSeo_Robots_Txt + */ + private $robots; + + protected function setUp() { + $this->robots = new PSeo_Robots_Txt(); + } + + public function testDefaults() { + $data = explode("\n", $this->robots->content()); + $this->assertEquals("User-Agent: *", $data[0], 'user agent'); + $this->assertEquals("Allow: /", $data[1]); + } + + public function testDisallowArray() { + $this->robots->blockUrls(array( + '/block1/', + '/block2/', + )); + + $data = explode("\n", $this->robots->content()); + + $this->assertEquals('Disallow: /block2/', $data[2]); + } + + public function testDisallowSingleUrl() { + $this->robots->blockUrl('/a-url-here/'); + + $data = explode("\n", $this->robots->content()); + + $this->assertEquals('Disallow: /a-url-here/', $data[1]); + + } + + public function testAllowArray() { + $this->robots->allowUrls(array( + '/allow/', + '/allowed/', + '/allow-this-one-too/' + )); + + $data = explode("\n", $this->robots->content()); + + $this->assertEquals('Allow: /allow-this-one-too/', $data[4]); + } + + public function testAllowSingleUrl() { + $this->robots->allowUrl('/a-url-here/'); + + $data = explode("\n", $this->robots->content()); + + $this->assertEquals('Allow: /a-url-here/', $data[2]); + } + + public function testUserAgent() { + $this->robots->setUserAgent('googlebot'); + + $data = explode("\n", $this->robots->content()); + + $this->assertEquals('User-Agent: googlebot', $data[0]); + + } + + protected function tearDown() { + unset($this->robots); + } + +} \ No newline at end of file
jugyo/flask-gae-template
857336755a3a17f72001627934a2ec73ac6ff183
rename bootstrap file
diff --git a/app.yaml b/app.yaml index 278b27a..a4d060a 100644 --- a/app.yaml +++ b/app.yaml @@ -1,14 +1,14 @@ application: app version: 1 runtime: python api_version: 1 handlers: - url: /favicon.ico static_files: static/favicon.ico upload: static/favicon.ico - url: /robots.txt static_files: static/robots.txt upload: static/robots.txt - url: /.* - script: main.py + script: bootstrap.py diff --git a/main.py b/bootstrap.py similarity index 100% rename from main.py rename to bootstrap.py
jugyo/flask-gae-template
d9c2e632e5c99d61c519b74aefe85512fef914e1
rename dir 'lib' => 'vendor'
diff --git a/main.py b/main.py index 5213f4d..eb3e3f6 100755 --- a/main.py +++ b/main.py @@ -1,6 +1,6 @@ import sys -sys.path.append('lib') +sys.path.append('vendor') from wsgiref.handlers import CGIHandler from app import app CGIHandler().run(app) diff --git a/setup.sh b/setup.sh index 98ab3bd..3eefb57 100755 --- a/setup.sh +++ b/setup.sh @@ -1,36 +1,36 @@ #!/bin/sh -mkdir lib +mkdir vendor libs='flask jinja2 werkzeug' for i in $libs do rm -rf $i done easy_install -U Flask for i in $libs do d=`easy_install -m $i | grep Using | awk '{print $2}'`/$i - cp -rf $d lib + cp -rf $d vendor done rm -rf .git rm setup.sh cat <<EOS > README.md my-app ====== Run ------ dev_appserver.py . Deploy ------ appcfg.py update . EOS \ No newline at end of file
jugyo/flask-gae-template
2f70f5dfab6ec0bf750133126797e1595c06fcfc
remove self at last
diff --git a/setup.sh b/setup.sh index 9dd898f..ca7a652 100755 --- a/setup.sh +++ b/setup.sh @@ -1,19 +1,20 @@ #!/bin/sh mkdir lib libs='flask jinja2 werkzeug' for i in $libs do rm -rf $i done easy_install -U Flask for i in $libs do d=`easy_install -m $i | grep Using | awk '{print $2}'`/$i cp -rf $d lib done rm -rf .git +rm setup.sh
jugyo/flask-gae-template
acac2598e4521cde1bb8169db2f9d1b8ff32025b
remove .git at last
diff --git a/setup.sh b/setup.sh index de959a5..9dd898f 100755 --- a/setup.sh +++ b/setup.sh @@ -1,17 +1,19 @@ #!/bin/sh mkdir lib libs='flask jinja2 werkzeug' for i in $libs do rm -rf $i done easy_install -U Flask for i in $libs do d=`easy_install -m $i | grep Using | awk '{print $2}'`/$i cp -rf $d lib done + +rm -rf .git
jugyo/flask-gae-template
707f7e47192e97903a01df150d169f1374625a65
fix a app url on local
diff --git a/README.md b/README.md index 810d3af..dd41847 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,33 @@ flask-gae-template ====== Setup ------ - git clone http://github.com/jugyo/flask-gae-template.git app - cd app - ./setup.sh + $ git clone http://github.com/jugyo/flask-gae-template.git app + $ cd app + $ ./setup.sh Run ------ dev_appserver.py . -and open 'http://localhost:8080/hello'. +and open 'http://localhost:8080/'. Deploy ------ You should fix application name of app.yaml before deploy. appcfg.py update . TODO ------ * sample for test See Also ------ [http://flask.pocoo.org/](http://flask.pocoo.org/)
jugyo/flask-gae-template
be1cc56f9300934e3ef13dfc1ddbf78094caff8d
modify README
diff --git a/README.md b/README.md index acf53fa..810d3af 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,33 @@ flask-gae-template ====== Setup ------ - git clone http://github.com/jugyo/flask-gae-template.git - cd flask-gae-template + git clone http://github.com/jugyo/flask-gae-template.git app + cd app ./setup.sh Run ------ dev_appserver.py . and open 'http://localhost:8080/hello'. Deploy ------ You should fix application name of app.yaml before deploy. appcfg.py update . TODO ------ * sample for test See Also ------ [http://flask.pocoo.org/](http://flask.pocoo.org/)
jugyo/flask-gae-template
6ae5fe79e649d5d92ea0d20150b46e2252f81f3b
changed sample to demo using DataStore
diff --git a/README.md b/README.md index e81c0d8..acf53fa 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,33 @@ flask-gae-template ====== Setup ------ git clone http://github.com/jugyo/flask-gae-template.git cd flask-gae-template ./setup.sh Run ------ dev_appserver.py . and open 'http://localhost:8080/hello'. Deploy ------ You should fix application name of app.yaml before deploy. appcfg.py update . TODO ------ -* sample for using DataStore * sample for test See Also ------ [http://flask.pocoo.org/](http://flask.pocoo.org/) diff --git a/app.py b/app.py index f42fa07..aab35a1 100644 --- a/app.py +++ b/app.py @@ -1,16 +1,21 @@ -from flask import Flask -from flask import render_template, request +# +# Flask Documentation: http://flask.pocoo.org/docs/ +# Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/ +# Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/ +# The Python Datastore API: http://code.google.com/appengine/docs/python/datastore/ +# -# if necessary -# from flask import redirect, url_for, session,\ -# abort, flash, get_flashed_messages, g, Response\ +from flask import Flask, url_for, render_template, request, redirect +from models import * app = Flask(__name__) @app.route('/') def index(): - return render_template('index.html') + return render_template('index.html', todos=Todo.all().order('-created_at')) [email protected]('/hello') -def hello(): - return render_template('hello.html', name=request.args.get('name')) [email protected]('/add', methods=["POST"]) +def add(): + todo = Todo(text=request.form['text']) + todo.save() + return redirect(url_for('index')) diff --git a/models.py b/models.py new file mode 100644 index 0000000..dfa2007 --- /dev/null +++ b/models.py @@ -0,0 +1,7 @@ +# The Python Datastore API: http://code.google.com/appengine/docs/python/datastore/ + +from google.appengine.ext import db + +class Todo(db.Model): + text = db.StringProperty() + created_at = db.DateTimeProperty(auto_now=True) diff --git a/static/screen.css b/static/screen.css index 43720d6..f42eb7c 100644 --- a/static/screen.css +++ b/static/screen.css @@ -1,6 +1,4 @@ body { - width: 600px; - margin: 60px auto; - text-align: center; + margin: 60px; font-family: 'Lucida Grande', sans-serif; } diff --git a/templates/hello.html b/templates/hello.html deleted file mode 100644 index 643a6ba..0000000 --- a/templates/hello.html +++ /dev/null @@ -1,4 +0,0 @@ -{% extends "layout.html" %} -{% block body %} - <div class="content">Hello {{ name }}!</div> -{% endblock %} diff --git a/templates/index.html b/templates/index.html index 30b32ac..acde3f6 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,7 +1,13 @@ {% extends "layout.html" %} {% block body %} - <form action="{{ url_for('hello') }}" method="get"> - <input type="text" name="name" /> - <input type="submit" value="hello"/> + <form action="{{ url_for('add') }}" method="post"> + <input type="text" name="text" /> + <input type="submit" value="add"/> </form> + + <ul> + {% for todo in todos %} + <li>{{ todo.text }}</li> + {% endfor %} + </ul> {% endblock %}
jugyo/flask-gae-template
d6152f201e7b43f8fbd98e29e5c93ccda4043858
ignore *.pyc
diff --git a/.gitignore b/.gitignore index b953268..04c3401 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ index.yaml +*.pyc
jugyo/flask-gae-template
07e065e67b99e736fb498837d25d82de651f9dc4
create main.py for bootstrap
diff --git a/app.py b/app.py old mode 100755 new mode 100644 index d59bf94..f42fa07 --- a/app.py +++ b/app.py @@ -1,23 +1,16 @@ -import sys -sys.path.append('lib') - from flask import Flask from flask import render_template, request # if necessary # from flask import redirect, url_for, session,\ # abort, flash, get_flashed_messages, g, Response\ app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/hello') def hello(): return render_template('hello.html', name=request.args.get('name')) - -if __name__ == '__main__': - from wsgiref.handlers import CGIHandler - CGIHandler().run(app) diff --git a/app.yaml b/app.yaml index edd1ea7..278b27a 100644 --- a/app.yaml +++ b/app.yaml @@ -1,14 +1,14 @@ application: app version: 1 runtime: python api_version: 1 handlers: - url: /favicon.ico static_files: static/favicon.ico upload: static/favicon.ico - url: /robots.txt static_files: static/robots.txt upload: static/robots.txt - url: /.* - script: app.py + script: main.py diff --git a/main.py b/main.py new file mode 100755 index 0000000..5213f4d --- /dev/null +++ b/main.py @@ -0,0 +1,6 @@ +import sys +sys.path.append('lib') + +from wsgiref.handlers import CGIHandler +from app import app +CGIHandler().run(app)
jugyo/flask-gae-template
d9be1c35ee2e4b9ae172d575d3f6b51379cec807
add @app.route('/')
diff --git a/app.py b/app.py index 9c343a6..d59bf94 100755 --- a/app.py +++ b/app.py @@ -1,20 +1,23 @@ import sys sys.path.append('lib') from flask import Flask -from flask import render_template +from flask import render_template, request # if necessary -# from flask import redirect, url_for, session, request,\ +# from flask import redirect, url_for, session,\ # abort, flash, get_flashed_messages, g, Response\ app = Flask(__name__) [email protected]('/hello/') [email protected]('/hello/<name>') -def hello(name=None): - return render_template('hello.html', name=name) [email protected]('/') +def index(): + return render_template('index.html') + [email protected]('/hello') +def hello(): + return render_template('hello.html', name=request.args.get('name')) if __name__ == '__main__': from wsgiref.handlers import CGIHandler CGIHandler().run(app) diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..30b32ac --- /dev/null +++ b/templates/index.html @@ -0,0 +1,7 @@ +{% extends "layout.html" %} +{% block body %} + <form action="{{ url_for('hello') }}" method="get"> + <input type="text" name="name" /> + <input type="submit" value="hello"/> + </form> +{% endblock %}
jugyo/flask-gae-template
9299a82ff0cabe2da23c324f0a3957379d8c14fa
add link to flask.pocoo.org
diff --git a/README.md b/README.md index 7adb11d..e81c0d8 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,34 @@ flask-gae-template ====== Setup ------ git clone http://github.com/jugyo/flask-gae-template.git cd flask-gae-template ./setup.sh Run ------ dev_appserver.py . and open 'http://localhost:8080/hello'. Deploy ------ You should fix application name of app.yaml before deploy. appcfg.py update . TODO ------ * sample for using DataStore * sample for test + +See Also +------ + +[http://flask.pocoo.org/](http://flask.pocoo.org/)
jugyo/flask-gae-template
22fa8bbbe90ad0a8b030238775aaec4214b167b7
add sample for using template
diff --git a/README.md b/README.md index b2988cf..7adb11d 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,29 @@ flask-gae-template ====== Setup ------ git clone http://github.com/jugyo/flask-gae-template.git cd flask-gae-template ./setup.sh Run ------ dev_appserver.py . +and open 'http://localhost:8080/hello'. + Deploy ------ You should fix application name of app.yaml before deploy. appcfg.py update . TODO ------ -* sample for using template +* sample for using DataStore * sample for test diff --git a/app.py b/app.py index 692f9bf..9c343a6 100755 --- a/app.py +++ b/app.py @@ -1,18 +1,20 @@ import sys sys.path.append('lib') from flask import Flask +from flask import render_template # if necessary # from flask import redirect, url_for, session, request,\ -# render_template, abort, flash, get_flashed_messages, g, Response\ +# abort, flash, get_flashed_messages, g, Response\ app = Flask(__name__) [email protected]('/') -def hello(): - return "Hello World!" [email protected]('/hello/') [email protected]('/hello/<name>') +def hello(name=None): + return render_template('hello.html', name=name) if __name__ == '__main__': from wsgiref.handlers import CGIHandler CGIHandler().run(app) diff --git a/static/screen.css b/static/screen.css new file mode 100644 index 0000000..43720d6 --- /dev/null +++ b/static/screen.css @@ -0,0 +1,6 @@ +body { + width: 600px; + margin: 60px auto; + text-align: center; + font-family: 'Lucida Grande', sans-serif; +} diff --git a/templates/hello.html b/templates/hello.html new file mode 100644 index 0000000..643a6ba --- /dev/null +++ b/templates/hello.html @@ -0,0 +1,4 @@ +{% extends "layout.html" %} +{% block body %} + <div class="content">Hello {{ name }}!</div> +{% endblock %} diff --git a/templates/layout.html b/templates/layout.html new file mode 100644 index 0000000..822bf4c --- /dev/null +++ b/templates/layout.html @@ -0,0 +1,11 @@ +<html> + <head> + <title>flask-gae-template</title> + <link rel=stylesheet type=text/css href="{{ url_for('static', filename='screen.css') }}"> + </head> + <body> + + {% block body %}{% endblock %} + + </body> +</html>
jugyo/flask-gae-template
f6d70e1efe01f7449160f0054bd0ca4e6b1bad9e
use 'lib' dir as library's dir
diff --git a/app.py b/app.py index 04f436a..692f9bf 100755 --- a/app.py +++ b/app.py @@ -1,15 +1,18 @@ +import sys +sys.path.append('lib') + from flask import Flask # if necessary # from flask import redirect, url_for, session, request,\ # render_template, abort, flash, get_flashed_messages, g, Response\ app = Flask(__name__) @app.route('/') def hello(): return "Hello World!" if __name__ == '__main__': from wsgiref.handlers import CGIHandler CGIHandler().run(app) diff --git a/setup.sh b/setup.sh index c690a8d..de959a5 100755 --- a/setup.sh +++ b/setup.sh @@ -1,15 +1,17 @@ #!/bin/sh -lib='flask jinja2 werkzeug' +mkdir lib -for i in $lib +libs='flask jinja2 werkzeug' + +for i in $libs do rm -rf $i done easy_install -U Flask -for i in $lib +for i in $libs do d=`easy_install -m $i | grep Using | awk '{print $2}'`/$i - cp -rf $d . + cp -rf $d lib done
jugyo/flask-gae-template
493133289e2544f84c890becb5ea949f134fe58b
added TODO to README
diff --git a/README.md b/README.md index 458b4b5..b2988cf 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,27 @@ flask-gae-template ====== Setup ------ git clone http://github.com/jugyo/flask-gae-template.git cd flask-gae-template ./setup.sh Run ------ dev_appserver.py . Deploy ------ You should fix application name of app.yaml before deploy. appcfg.py update . + +TODO +------ + +* sample for using template +* sample for test
jugyo/flask-gae-template
d37c29122b74c0361894bc85d6f8b9222641eb94
fix easy_install option
diff --git a/setup.sh b/setup.sh index 8a8ad1c..c690a8d 100755 --- a/setup.sh +++ b/setup.sh @@ -1,15 +1,15 @@ #!/bin/sh lib='flask jinja2 werkzeug' for i in $lib do rm -rf $i done -easy_install -U -i http://pypi.python.jp/ Flask +easy_install -U Flask for i in $lib do d=`easy_install -m $i | grep Using | awk '{print $2}'`/$i cp -rf $d . done
jugyo/flask-gae-template
dc78837874065fc5dc60346c75b33bdd5c9ead38
changed method name for path '/'
diff --git a/app.py b/app.py index 7fec4fa..04f436a 100755 --- a/app.py +++ b/app.py @@ -1,15 +1,15 @@ from flask import Flask # if necessary # from flask import redirect, url_for, session, request,\ # render_template, abort, flash, get_flashed_messages, g, Response\ app = Flask(__name__) @app.route('/') -def login(): +def hello(): return "Hello World!" if __name__ == '__main__': from wsgiref.handlers import CGIHandler CGIHandler().run(app)
jugyo/flask-gae-template
673d7a0b862133158537bc0b6860fa36dfa86412
wrote about deploy
diff --git a/README.md b/README.md index 12adad2..458b4b5 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,21 @@ flask-gae-template ====== Setup ------ git clone http://github.com/jugyo/flask-gae-template.git cd flask-gae-template ./setup.sh Run ------ dev_appserver.py . + +Deploy +------ + +You should fix application name of app.yaml before deploy. + + appcfg.py update .
jugyo/flask-gae-template
3c5df013334d547f6c42dae526f0f77d5e14eda2
modified README
diff --git a/README.md b/README.md index bbc6805..12adad2 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,14 @@ flask-gae-template ====== Setup ------ + git clone http://github.com/jugyo/flask-gae-template.git + cd flask-gae-template ./setup.sh + +Run +------ + + dev_appserver.py .
jugyo/flask-gae-template
8edd991ef3265b54a59f0c558695b12e18499f00
modified app.yaml
diff --git a/app.yaml b/app.yaml index 1df6ca5..edd1ea7 100644 --- a/app.yaml +++ b/app.yaml @@ -1,14 +1,14 @@ -application: translate +application: app version: 1 runtime: python api_version: 1 handlers: - url: /favicon.ico static_files: static/favicon.ico upload: static/favicon.ico - url: /robots.txt static_files: static/robots.txt upload: static/robots.txt - url: /.* script: app.py
jugyo/flask-gae-template
2713f52057e59dca12de438a58ad3e32b4e4ff09
ignore index.yaml
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b953268 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +index.yaml
jugyo/flask-gae-template
ebc65e80c1031f4d6fa7ebb53e8c4f75cc13e888
create a setup script
diff --git a/README.md b/README.md index ccf528b..bbc6805 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,7 @@ flask-gae-template ====== + +Setup +------ + + ./setup.sh diff --git a/setup.sh b/setup.sh new file mode 100755 index 0000000..8a8ad1c --- /dev/null +++ b/setup.sh @@ -0,0 +1,15 @@ +#!/bin/sh +lib='flask jinja2 werkzeug' + +for i in $lib +do + rm -rf $i +done + +easy_install -U -i http://pypi.python.jp/ Flask + +for i in $lib +do + d=`easy_install -m $i | grep Using | awk '{print $2}'`/$i + cp -rf $d . +done
namin/lua
c7be5ffdd8ab73198b8296f7120c68f49929b470
formatting
diff --git a/reading-order-recommended-by-mike-pall.md b/reading-order-recommended-by-mike-pall.md index b11b8ca..72880eb 100644 --- a/reading-order-recommended-by-mike-pall.md +++ b/reading-order-recommended-by-mike-pall.md @@ -1,68 +1,69 @@ Recommended reading order +========================= 1. lmathlib.c, lstrlib.c Get familiar with the external C API. Don't bother with the pattern matcher though. Just the easy functions. 2. lapi.c Check how the API is implemented internally. Only skim this to get a feeling for the code. Cross-reference to lua.h and luaconf.h as needed. 3. lobject.h Tagged values and object representation. Skim through this first. You'll want to keep a window with this file open all the time. 4. lstate.h State objects. Ditto. 5. lopcodes.h Bytecode instruction format and opcode definitions. Easy. 6. lvm.c - Scroll down to luaV_execute, the main interpreter loop. See how + Scroll down to `luaV_execute`, the main interpreter loop. See how all of the instructions are implemented. Skip the details for now. Reread later. 7. ldo.c Calls, stacks, exceptions, coroutines. Tough read. 8. lstring.c String interning. Cute, huh? 9. ltable.c Hash tables and arrays. Tricky code. 10. ltm.c Metamethod handling. Reread all of lvm.c now. You may want to reread lapi.c now. 11. ldebug.c Surprise waiting for you. Abstract interpretation is used to find object names for tracebacks. Does bytecode verification, too. 12. lparser.c, lcode.c Recursive descent parser, targetting a register-based VM. Start from chunk() and work your way through. Read the expression parser and the code generator parts last. 13. lgc.c Incremental garbage collector. Take your time. Read all the other files as you see references to them. Don't let your stack get too deep though. source: [Reddit comment](http://www.reddit.com/comments/63hth/ask_reddit_which_oss_codebases_out_there_are_so/c02pxbp) \ No newline at end of file
wjzhangq/python-msn-bot
0ea46bd66d5b5def11e7b9b0afd34f45a5726d02
in hand php
diff --git a/msnbot.py b/msnbot.py index a746986..843fda7 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,310 +1,310 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb import os, sys, select, socket, time, re import threading import urllib,subprocess m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 -CMD = 'php -f "' + os.getcwd() + os.sep + 'r.php"' +CMD = 'php -f "' + os.getcwd() + os.sep + 'php' + os.sep . 'handle_msg.php.php"' def null(s): "Null function, useful to void debug ones" pass msnlib.debug = null msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 argv = [str(x) for x in lines] + argv.append(str(email)) argv.append(str(HOST)) argv.append(str(PORT)) - argv.append(str(email)) fp = subprocess.Popen(CMD + ' "' + urllib.quote_plus('\n\r\n'.join(argv)) + '"', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) #m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): global m tmp = str.split(':', 1) if len(tmp) == 1: msg = 'Unrecognized Format'; else: if tmp[0] == 'send': tmp1 = tmp[1].split(':', 1) if len(tmp1) == 1: msg = 'Format error<send:email:msg>' else: email = tmp1[0] body = tmp1[1] if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): msg = 'Eamil not invalid' else: mylock.acquire() if m.users.has_key(email): m.users[email].priv['typing'] = 0 m.change_status('online') r = m.sendmsg(email, body) mylock.release() if r == 1: msg = 'Message for %s queued for delivery' % email elif r == 2: msg = 'Message for %s delivery' % email elif r == -2: msg = 'Message too big' else: msg = 'Error %d sending message' % r else: msg = 'Unrecognized Command' return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) debug('bind ' + HOST + ':' + str(PORT)) except socket.error: sys.exit('call to bind fail') #muti threading class msn_wait(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='msn wait') def run(self): global m try: m.login() debug('login done') except 'AuthError', info: errno = int(info[0]) if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] debug('Error: %s (%s)' % (desc, errno)) quit(1) except KeyboardInterrupt: quit() except ('SocketError', socket.error), info: debug('Network error: ' + str(info)) quit(1) except: debug('Exception logging in') quit(1) # call sync to get the lists and refresh if m.sync(): debug('sync done') list_complete = 0 else: debug('Error syncing users') m.change_status('online'); while True: fds = m.pollable() infd = fds[0] outfd = fds[1] try: fds = select.select(infd, outfd, [], timeout) except KeyboardInterrupt: quit() for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ try: mylock.acquire() m.read(i) mylock.release() except ('SocketError', socket.error), err: if i != m: if i.msgqueue: nick = email2nick(i.emails[0]) dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) for msg in i.msgqueue: debug(msg ) m.close(i) else: debug('\nMain socket closed (%s)' % str(err)) quit(1) except 'XFRError', err: debug("\rXFR Error: %s" % str(err)) mylock = threading.RLock() th = msn_wait(); th.start(); mySocket.listen(10) while True: try: conn, addr = mySocket.accept() data = conn.recv(10240) if not data: continue msg = parse_cmd(data) conn.send(msg) conn.close() except KeyboardInterrupt: debug('ctrl + c') quit() except Exception,e: debug(str(e)) debug('Main has terminal') quit(1) diff --git a/r.php b/php/handle_msg.php similarity index 100% rename from r.php rename to php/handle_msg.php
wjzhangq/python-msn-bot
37604f745e8522d99c33215399ba847cddead587
revice msg do with php
diff --git a/msnbot.py b/msnbot.py index 387812d..a746986 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,311 +1,310 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb -import sys, select, socket, time, re +import os, sys, select, socket, time, re import threading -import json, urllib +import urllib,subprocess m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 CMD = 'php -f "' + os.getcwd() + os.sep + 'r.php"' def null(s): "Null function, useful to void debug ones" pass msnlib.debug = null msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 - argv = [] - argv.append(HOST) - arvg.append(PORT) - argv.append(email) - argv.extend(lines) - fp = subprocess.Popen(CMD + ' ' + urllib.quote_plus(json.dumps(argv)), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) + argv = [str(x) for x in lines] + argv.append(str(HOST)) + argv.append(str(PORT)) + argv.append(str(email)) + fp = subprocess.Popen(CMD + ' "' + urllib.quote_plus('\n\r\n'.join(argv)) + '"', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) #m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): global m tmp = str.split(':', 1) if len(tmp) == 1: msg = 'Unrecognized Format'; else: if tmp[0] == 'send': tmp1 = tmp[1].split(':', 1) if len(tmp1) == 1: msg = 'Format error<send:email:msg>' else: email = tmp1[0] body = tmp1[1] if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): msg = 'Eamil not invalid' else: mylock.acquire() if m.users.has_key(email): m.users[email].priv['typing'] = 0 m.change_status('online') r = m.sendmsg(email, body) mylock.release() if r == 1: msg = 'Message for %s queued for delivery' % email elif r == 2: msg = 'Message for %s delivery' % email elif r == -2: msg = 'Message too big' else: msg = 'Error %d sending message' % r else: msg = 'Unrecognized Command' return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) debug('bind ' + HOST + ':' + str(PORT)) except socket.error: sys.exit('call to bind fail') #muti threading class msn_wait(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='msn wait') def run(self): global m try: m.login() debug('login done') except 'AuthError', info: errno = int(info[0]) if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] debug('Error: %s (%s)' % (desc, errno)) quit(1) except KeyboardInterrupt: quit() except ('SocketError', socket.error), info: debug('Network error: ' + str(info)) quit(1) except: debug('Exception logging in') quit(1) # call sync to get the lists and refresh if m.sync(): debug('sync done') list_complete = 0 else: debug('Error syncing users') m.change_status('online'); while True: fds = m.pollable() infd = fds[0] outfd = fds[1] try: fds = select.select(infd, outfd, [], timeout) except KeyboardInterrupt: quit() for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ try: mylock.acquire() m.read(i) mylock.release() except ('SocketError', socket.error), err: if i != m: if i.msgqueue: nick = email2nick(i.emails[0]) dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) for msg in i.msgqueue: debug(msg ) m.close(i) else: debug('\nMain socket closed (%s)' % str(err)) quit(1) except 'XFRError', err: debug("\rXFR Error: %s" % str(err)) mylock = threading.RLock() th = msn_wait(); th.start(); mySocket.listen(10) while True: try: conn, addr = mySocket.accept() data = conn.recv(10240) if not data: continue msg = parse_cmd(data) conn.send(msg) conn.close() except KeyboardInterrupt: debug('ctrl + c') quit() except Exception,e: debug(str(e)) debug('Main has terminal') quit(1) diff --git a/r.php b/r.php index 65edd8c..8db25bf 100755 --- a/r.php +++ b/r.php @@ -1,3 +1,8 @@ <?php -echo 'kkk'; +if (isset($argv[1])){ + $tmp = urldecode($argv[1]); + $arr = explode("\n\r\n", $tmp); + file_put_contents('a.log', "\n" . date('Y-m-d H:i:s') . "\r" . var_export($arr, true), FILE_APPEND); +} + ?> \ No newline at end of file
wjzhangq/python-msn-bot
ec5c801de32bd5fdde73136bd9fc72f0e500ec42
add php
diff --git a/msnbot.py b/msnbot.py index 4a96da0..387812d 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,304 +1,311 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb import sys, select, socket, time, re import threading +import json, urllib + m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 +CMD = 'php -f "' + os.getcwd() + os.sep + 'r.php"' def null(s): "Null function, useful to void debug ones" pass msnlib.debug = null msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 - print(email) - print(lines) - m.sendmsg(email, lines[-1]) + argv = [] + argv.append(HOST) + arvg.append(PORT) + argv.append(email) + argv.extend(lines) + fp = subprocess.Popen(CMD + ' ' + urllib.quote_plus(json.dumps(argv)), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) + #m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): global m tmp = str.split(':', 1) if len(tmp) == 1: msg = 'Unrecognized Format'; else: if tmp[0] == 'send': tmp1 = tmp[1].split(':', 1) if len(tmp1) == 1: msg = 'Format error<send:email:msg>' else: email = tmp1[0] body = tmp1[1] if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): msg = 'Eamil not invalid' else: mylock.acquire() if m.users.has_key(email): m.users[email].priv['typing'] = 0 m.change_status('online') r = m.sendmsg(email, body) mylock.release() if r == 1: msg = 'Message for %s queued for delivery' % email elif r == 2: msg = 'Message for %s delivery' % email elif r == -2: msg = 'Message too big' else: msg = 'Error %d sending message' % r else: msg = 'Unrecognized Command' return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) debug('bind ' + HOST + ':' + str(PORT)) except socket.error: sys.exit('call to bind fail') #muti threading class msn_wait(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='msn wait') def run(self): global m try: m.login() debug('login done') except 'AuthError', info: errno = int(info[0]) if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] debug('Error: %s (%s)' % (desc, errno)) quit(1) except KeyboardInterrupt: quit() except ('SocketError', socket.error), info: debug('Network error: ' + str(info)) quit(1) except: debug('Exception logging in') quit(1) # call sync to get the lists and refresh if m.sync(): debug('sync done') list_complete = 0 else: debug('Error syncing users') m.change_status('online'); while True: fds = m.pollable() infd = fds[0] outfd = fds[1] try: fds = select.select(infd, outfd, [], timeout) except KeyboardInterrupt: quit() for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ try: mylock.acquire() m.read(i) mylock.release() except ('SocketError', socket.error), err: if i != m: if i.msgqueue: nick = email2nick(i.emails[0]) dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) for msg in i.msgqueue: debug(msg ) m.close(i) else: debug('\nMain socket closed (%s)' % str(err)) quit(1) except 'XFRError', err: debug("\rXFR Error: %s" % str(err)) mylock = threading.RLock() th = msn_wait(); th.start(); mySocket.listen(10) while True: try: conn, addr = mySocket.accept() data = conn.recv(10240) if not data: continue msg = parse_cmd(data) conn.send(msg) conn.close() except KeyboardInterrupt: debug('ctrl + c') quit() except Exception,e: debug(str(e)) debug('Main has terminal') quit(1) diff --git a/r.php b/r.php new file mode 100755 index 0000000..65edd8c --- /dev/null +++ b/r.php @@ -0,0 +1,3 @@ +<?php +echo 'kkk'; +?> \ No newline at end of file
wjzhangq/python-msn-bot
9cbc33d4416a00d5760cd6a256cca912127110ce
close msn debug
diff --git a/msnbot.py b/msnbot.py index bfad0d5..4a96da0 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,304 +1,304 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb import sys, select, socket, time, re import threading m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 def null(s): "Null function, useful to void debug ones" pass -#msnlib.debug = null -#msncb.debug = null +msnlib.debug = null +msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 print(email) print(lines) m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): global m tmp = str.split(':', 1) if len(tmp) == 1: msg = 'Unrecognized Format'; else: if tmp[0] == 'send': tmp1 = tmp[1].split(':', 1) if len(tmp1) == 1: msg = 'Format error<send:email:msg>' else: email = tmp1[0] body = tmp1[1] if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): msg = 'Eamil not invalid' else: mylock.acquire() if m.users.has_key(email): m.users[email].priv['typing'] = 0 m.change_status('online') r = m.sendmsg(email, body) mylock.release() if r == 1: msg = 'Message for %s queued for delivery' % email elif r == 2: msg = 'Message for %s delivery' % email elif r == -2: msg = 'Message too big' else: msg = 'Error %d sending message' % r else: msg = 'Unrecognized Command' return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) debug('bind ' + HOST + ':' + str(PORT)) except socket.error: sys.exit('call to bind fail') #muti threading class msn_wait(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='msn wait') def run(self): global m try: m.login() debug('login done') except 'AuthError', info: errno = int(info[0]) if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] debug('Error: %s (%s)' % (desc, errno)) quit(1) except KeyboardInterrupt: quit() except ('SocketError', socket.error), info: debug('Network error: ' + str(info)) quit(1) except: debug('Exception logging in') quit(1) # call sync to get the lists and refresh if m.sync(): debug('sync done') list_complete = 0 else: debug('Error syncing users') m.change_status('online'); while True: fds = m.pollable() infd = fds[0] outfd = fds[1] try: fds = select.select(infd, outfd, [], timeout) except KeyboardInterrupt: quit() for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ try: mylock.acquire() m.read(i) mylock.release() except ('SocketError', socket.error), err: if i != m: if i.msgqueue: nick = email2nick(i.emails[0]) dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) for msg in i.msgqueue: debug(msg ) m.close(i) else: debug('\nMain socket closed (%s)' % str(err)) quit(1) except 'XFRError', err: debug("\rXFR Error: %s" % str(err)) mylock = threading.RLock() th = msn_wait(); th.start(); mySocket.listen(10) while True: try: conn, addr = mySocket.accept() data = conn.recv(10240) if not data: continue msg = parse_cmd(data) conn.send(msg) conn.close() except KeyboardInterrupt: debug('ctrl + c') quit() except Exception,e: debug(str(e)) debug('Main has terminal') quit(1)
wjzhangq/python-msn-bot
46448882d56bd205cede71f2ad665a0a7e55ea56
fix a bug
diff --git a/msnbot.py b/msnbot.py index f00716a..bfad0d5 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,302 +1,304 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb import sys, select, socket, time, re import threading m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 def null(s): "Null function, useful to void debug ones" pass -msnlib.debug = null -msncb.debug = null +#msnlib.debug = null +#msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 print(email) print(lines) m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): global m tmp = str.split(':', 1) if len(tmp) == 1: msg = 'Unrecognized Format'; else: if tmp[0] == 'send': tmp1 = tmp[1].split(':', 1) if len(tmp1) == 1: msg = 'Format error<send:email:msg>' else: email = tmp1[0] body = tmp1[1] if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): msg = 'Eamil not invalid' else: mylock.acquire() if m.users.has_key(email): m.users[email].priv['typing'] = 0 m.change_status('online') r = m.sendmsg(email, body) mylock.release() if r == 1: msg = 'Message for %s queued for delivery' % email elif r == 2: - result = 'Message for %s delivery' % email + msg = 'Message for %s delivery' % email elif r == -2: msg = 'Message too big' else: msg = 'Error %d sending message' % r else: msg = 'Unrecognized Command' return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) debug('bind ' + HOST + ':' + str(PORT)) except socket.error: sys.exit('call to bind fail') #muti threading class msn_wait(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='msn wait') def run(self): global m try: m.login() debug('login done') except 'AuthError', info: errno = int(info[0]) if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] debug('Error: %s (%s)' % (desc, errno)) quit(1) except KeyboardInterrupt: quit() except ('SocketError', socket.error), info: debug('Network error: ' + str(info)) quit(1) except: debug('Exception logging in') quit(1) # call sync to get the lists and refresh if m.sync(): debug('sync done') list_complete = 0 else: debug('Error syncing users') m.change_status('online'); while True: fds = m.pollable() infd = fds[0] outfd = fds[1] try: fds = select.select(infd, outfd, [], timeout) except KeyboardInterrupt: quit() for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ try: mylock.acquire() m.read(i) mylock.release() except ('SocketError', socket.error), err: if i != m: if i.msgqueue: nick = email2nick(i.emails[0]) dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) for msg in i.msgqueue: debug(msg ) m.close(i) else: debug('\nMain socket closed (%s)' % str(err)) quit(1) except 'XFRError', err: debug("\rXFR Error: %s" % str(err)) mylock = threading.RLock() th = msn_wait(); th.start(); mySocket.listen(10) while True: try: conn, addr = mySocket.accept() data = conn.recv(10240) if not data: continue msg = parse_cmd(data) conn.send(msg) conn.close() except KeyboardInterrupt: debug('ctrl + c') quit() - except: + except Exception,e: + debug(str(e)) debug('Main has terminal') quit(1) +
wjzhangq/python-msn-bot
4abb01b580aac0d4765a89d78682347e4bebae60
back to muti thread, but have bug
diff --git a/msnbot.py b/msnbot.py index c5421eb..f00716a 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,287 +1,302 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb import sys, select, socket, time, re import threading m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 def null(s): "Null function, useful to void debug ones" pass msnlib.debug = null msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 print(email) print(lines) m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): global m tmp = str.split(':', 1) if len(tmp) == 1: msg = 'Unrecognized Format'; else: if tmp[0] == 'send': tmp1 = tmp[1].split(':', 1) if len(tmp1) == 1: msg = 'Format error<send:email:msg>' else: email = tmp1[0] body = tmp1[1] if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): msg = 'Eamil not invalid' else: + mylock.acquire() if m.users.has_key(email): m.users[email].priv['typing'] = 0 m.change_status('online') r = m.sendmsg(email, body) + mylock.release() if r == 1: msg = 'Message for %s queued for delivery' % email elif r == 2: result = 'Message for %s delivery' % email elif r == -2: msg = 'Message too big' else: msg = 'Error %d sending message' % r else: msg = 'Unrecognized Command' return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) debug('bind ' + HOST + ':' + str(PORT)) except socket.error: sys.exit('call to bind fail') -try: - m.login() - debug('login done') -except 'AuthError', info: - errno = int(info[0]) - if not msncb.error_table.has_key(errno): - desc = 'Unknown' - else: - desc = msncb.error_table[errno] - debug('Error: %s (%s)' % (desc, errno)) - quit(1) -except KeyboardInterrupt: - quit() -except ('SocketError', socket.error), info: - debug('Network error: ' + str(info)) - quit(1) -except: - debug('Exception logging in') - quit(1) - -# call sync to get the lists and refresh -if m.sync(): - debug('sync done') - list_complete = 0 -else: - debug('Error syncing users') - -m.change_status('online'); - -#listen -mySocket.listen(1) +#muti threading +class msn_wait(threading.Thread): + def __init__(self): + threading.Thread.__init__(self, name='msn wait') + + def run(self): + global m + try: + m.login() + debug('login done') + except 'AuthError', info: + errno = int(info[0]) + if not msncb.error_table.has_key(errno): + desc = 'Unknown' + else: + desc = msncb.error_table[errno] + debug('Error: %s (%s)' % (desc, errno)) + quit(1) + except KeyboardInterrupt: + quit() + except ('SocketError', socket.error), info: + debug('Network error: ' + str(info)) + quit(1) + except: + debug('Exception logging in') + quit(1) + + # call sync to get the lists and refresh + if m.sync(): + debug('sync done') + list_complete = 0 + else: + debug('Error syncing users') + + m.change_status('online'); + while True: + fds = m.pollable() + infd = fds[0] + outfd = fds[1] + + try: + fds = select.select(infd, outfd, [], timeout) + except KeyboardInterrupt: + quit() + for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ + try: + mylock.acquire() + m.read(i) + mylock.release() + except ('SocketError', socket.error), err: + if i != m: + if i.msgqueue: + nick = email2nick(i.emails[0]) + dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) + for msg in i.msgqueue: + debug(msg ) + m.close(i) + else: + debug('\nMain socket closed (%s)' % str(err)) + quit(1) + except 'XFRError', err: + debug("\rXFR Error: %s" % str(err)) + + + +mylock = threading.RLock() +th = msn_wait(); +th.start(); + + +mySocket.listen(10) while True: - fds = m.pollable() - infd = fds[0] - outfd = fds[1] - infd.append(mySocket.fileno()) - try: - fds = select.select(infd, outfd, [], timeout) + conn, addr = mySocket.accept() + data = conn.recv(10240) + if not data: + continue + msg = parse_cmd(data) + conn.send(msg) + conn.close() except KeyboardInterrupt: + debug('ctrl + c') quit() - for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ - if i == mySocket.fileno(): - try: - conn, addr = mySocket.accept() - data = conn.recv(10240) - if not data: - continue - msg = parse_cmd(data) - conn.send(msg) - conn.close() - except KeyboardInterrupt: - debug('ctrl + c') - quit() - except: - debug('Main has terminal') - quit(1) - else: - try: - m.read(i) - except ('SocketError', socket.error), err: - if i != m: - if i.msgqueue: - nick = email2nick(i.emails[0]) - dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) - for msg in i.msgqueue: - debug(msg ) - m.close(i) - else: - debug('\nMain socket closed (%s)' % str(err)) - quit(1) - except 'XFRError', err: - debug("\rXFR Error: %s" % str(err)) + except: + debug('Main has terminal') + quit(1)
wjzhangq/python-msn-bot
52a345f6821c1ee828fa1e0bd9722229f2ef05f9
change to sigle thread
diff --git a/msnbot.py b/msnbot.py index a24a977..c5421eb 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,300 +1,287 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb import sys, select, socket, time, re import threading m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 def null(s): "Null function, useful to void debug ones" pass msnlib.debug = null msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 print(email) print(lines) m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): global m tmp = str.split(':', 1) if len(tmp) == 1: msg = 'Unrecognized Format'; else: if tmp[0] == 'send': tmp1 = tmp[1].split(':', 1) if len(tmp1) == 1: msg = 'Format error<send:email:msg>' else: email = tmp1[0] body = tmp1[1] if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): msg = 'Eamil not invalid' else: - mylock.acquire() - print m.users + if m.users.has_key(email): + m.users[email].priv['typing'] = 0 + m.change_status('online') r = m.sendmsg(email, body) - mylock.release() if r == 1: msg = 'Message for %s queued for delivery' % email elif r == 2: result = 'Message for %s delivery' % email elif r == -2: msg = 'Message too big' else: msg = 'Error %d sending message' % r else: msg = 'Unrecognized Command' return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) debug('bind ' + HOST + ':' + str(PORT)) except socket.error: sys.exit('call to bind fail') -#muti threading -class msn_wait(threading.Thread): - def __init__(self): - threading.Thread.__init__(self, name='msn wait') - - def run(self): - global m - try: - m.login() - debug('login done') - except 'AuthError', info: - errno = int(info[0]) - if not msncb.error_table.has_key(errno): - desc = 'Unknown' - else: - desc = msncb.error_table[errno] - debug('Error: %s (%s)' % (desc, errno)) - quit(1) - except KeyboardInterrupt: - quit() - except ('SocketError', socket.error), info: - debug('Network error: ' + str(info)) - quit(1) - except: - debug('Exception logging in') - quit(1) - - # call sync to get the lists and refresh - if m.sync(): - debug('sync done') - list_complete = 0 - else: - debug('Error syncing users') - - m.change_status('online'); - - while True: - fds = m.pollable() - infd = fds[0] - outfd = fds[1] - - try: - fds = select.select(infd, outfd, [], timeout) - except KeyboardInterrupt: - quit() - for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ - try: - mylock.acquire() - m.read(i) - mylock.release() - except ('SocketError', socket.error), err: - if i != m: - if i.msgqueue: - nick = email2nick(i.emails[0]) - dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) - for msg in i.msgqueue: - debug(msg ) - m.close(i) - else: - debug('\nMain socket closed (%s)' % str(err)) - quit(1) - except 'XFRError', err: - debug("\rXFR Error: %s" % str(err)) - - - -mylock = threading.RLock() -th = msn_wait(); -th.start(); - +try: + m.login() + debug('login done') +except 'AuthError', info: + errno = int(info[0]) + if not msncb.error_table.has_key(errno): + desc = 'Unknown' + else: + desc = msncb.error_table[errno] + debug('Error: %s (%s)' % (desc, errno)) + quit(1) +except KeyboardInterrupt: + quit() +except ('SocketError', socket.error), info: + debug('Network error: ' + str(info)) + quit(1) +except: + debug('Exception logging in') + quit(1) + +# call sync to get the lists and refresh +if m.sync(): + debug('sync done') + list_complete = 0 +else: + debug('Error syncing users') + +m.change_status('online'); + +#listen +mySocket.listen(1) -mySocket.listen(10) while True: + fds = m.pollable() + infd = fds[0] + outfd = fds[1] + infd.append(mySocket.fileno()) + try: - conn, addr = mySocket.accept() - data = conn.recv(10240) - if not data: - continue - msg = parse_cmd(data) - conn.send(msg) - conn.close() + fds = select.select(infd, outfd, [], timeout) except KeyboardInterrupt: - debug('ctrl + c') quit() - except: - debug('Main has terminal') - quit(1) + for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ + if i == mySocket.fileno(): + try: + conn, addr = mySocket.accept() + data = conn.recv(10240) + if not data: + continue + msg = parse_cmd(data) + conn.send(msg) + conn.close() + except KeyboardInterrupt: + debug('ctrl + c') + quit() + except: + debug('Main has terminal') + quit(1) + else: + try: + m.read(i) + except ('SocketError', socket.error), err: + if i != m: + if i.msgqueue: + nick = email2nick(i.emails[0]) + dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) + for msg in i.msgqueue: + debug(msg ) + m.close(i) + else: + debug('\nMain socket closed (%s)' % str(err)) + quit(1) + except 'XFRError', err: + debug("\rXFR Error: %s" % str(err))
wjzhangq/python-msn-bot
87a9f793c132f6c3e9487986898ec8d1aa5fa755
add threaing Rlock
diff --git a/msnbot.py b/msnbot.py index 11fd556..a24a977 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,292 +1,300 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb import sys, select, socket, time, re import threading m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 def null(s): "Null function, useful to void debug ones" pass msnlib.debug = null msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 print(email) print(lines) m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): + global m tmp = str.split(':', 1) if len(tmp) == 1: msg = 'Unrecognized Format'; else: if tmp[0] == 'send': tmp1 = tmp[1].split(':', 1) if len(tmp1) == 1: msg = 'Format error<send:email:msg>' else: email = tmp1[0] body = tmp1[1] if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): msg = 'Eamil not invalid' else: + mylock.acquire() + print m.users r = m.sendmsg(email, body) + mylock.release() if r == 1: msg = 'Message for %s queued for delivery' % email elif r == 2: result = 'Message for %s delivery' % email elif r == -2: msg = 'Message too big' else: msg = 'Error %d sending message' % r else: msg = 'Unrecognized Command' return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) + debug('bind ' + HOST + ':' + str(PORT)) except socket.error: sys.exit('call to bind fail') #muti threading class msn_wait(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='msn wait') def run(self): global m try: m.login() debug('login done') except 'AuthError', info: errno = int(info[0]) if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] debug('Error: %s (%s)' % (desc, errno)) quit(1) except KeyboardInterrupt: quit() except ('SocketError', socket.error), info: debug('Network error: ' + str(info)) quit(1) except: debug('Exception logging in') quit(1) # call sync to get the lists and refresh if m.sync(): debug('sync done') list_complete = 0 else: debug('Error syncing users') m.change_status('online'); while True: fds = m.pollable() infd = fds[0] outfd = fds[1] try: fds = select.select(infd, outfd, [], timeout) except KeyboardInterrupt: quit() - for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ try: + mylock.acquire() m.read(i) - debug('m read'); + mylock.release() except ('SocketError', socket.error), err: if i != m: if i.msgqueue: nick = email2nick(i.emails[0]) dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) for msg in i.msgqueue: debug(msg ) m.close(i) else: debug('\nMain socket closed (%s)' % str(err)) quit(1) except 'XFRError', err: debug("\rXFR Error: %s" % str(err)) + + +mylock = threading.RLock() th = msn_wait(); th.start(); mySocket.listen(10) while True: try: conn, addr = mySocket.accept() data = conn.recv(10240) if not data: continue msg = parse_cmd(data) conn.send(msg) conn.close() except KeyboardInterrupt: debug('ctrl + c') quit() except: debug('Main has terminal') quit(1)
wjzhangq/python-msn-bot
1c3aa00253cbdd9d6fed52286f0f59494f26b420
msnd for threadin
diff --git a/msnbot.py b/msnbot.py index f00a87a..11fd556 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,272 +1,292 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb -import sys, select, socket, time +import sys, select, socket, time, re import threading m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' HOST = '127.0.0.1' PORT = 8888 def null(s): "Null function, useful to void debug ones" pass msnlib.debug = null msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 print(email) print(lines) m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': out = ('%s (%s) ' % (email, nick)) \ + 'has added you to his contact list' debug(out) beep() elif type == 'FL': out = ('%s (%s) ' % (email, nick)) \ + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add def parse_cmd(str): - data = str.split(':', 2) - if len(data) == 3: - return data - return None + tmp = str.split(':', 1) + if len(tmp) == 1: + msg = 'Unrecognized Format'; + else: + if tmp[0] == 'send': + tmp1 = tmp[1].split(':', 1) + if len(tmp1) == 1: + msg = 'Format error<send:email:msg>' + else: + email = tmp1[0] + body = tmp1[1] + if not re.match(r'[\w\_\.]+@[\w\_]+(\.[\w\_]+){1,3}', email): + msg = 'Eamil not invalid' + else: + r = m.sendmsg(email, body) + if r == 1: + msg = 'Message for %s queued for delivery' % email + elif r == 2: + result = 'Message for %s delivery' % email + elif r == -2: + msg = 'Message too big' + else: + msg = 'Error %d sending message' % r + else: + msg = 'Unrecognized Command' + + return msg mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mySocket.bind((HOST, PORT)) except socket.error: sys.exit('call to bind fail') -try: - m.login() - debug('login done') -except 'AuthError', info: - errno = int(info[0]) - if not msncb.error_table.has_key(errno): - desc = 'Unknown' - else: - desc = msncb.error_table[errno] - debug('Error: %s (%s)' % (desc, errno)) - quit(1) -except KeyboardInterrupt: - quit() -except ('SocketError', socket.error), info: - debug('Network error: ' + str(info)) - quit(1) -except: - debug('Exception logging in') - quit(1) - -# call sync to get the lists and refresh -if m.sync(): - debug('sync done') - list_complete = 0 -else: - debug('Error syncing users') - -m.change_status('online'); - #muti threading class msn_wait(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='msn wait') def run(self): global m + try: + m.login() + debug('login done') + except 'AuthError', info: + errno = int(info[0]) + if not msncb.error_table.has_key(errno): + desc = 'Unknown' + else: + desc = msncb.error_table[errno] + debug('Error: %s (%s)' % (desc, errno)) + quit(1) + except KeyboardInterrupt: + quit() + except ('SocketError', socket.error), info: + debug('Network error: ' + str(info)) + quit(1) + except: + debug('Exception logging in') + quit(1) + + # call sync to get the lists and refresh + if m.sync(): + debug('sync done') + list_complete = 0 + else: + debug('Error syncing users') + + m.change_status('online'); + while True: fds = m.pollable() infd = fds[0] outfd = fds[1] try: fds = select.select(infd, outfd, [], timeout) except KeyboardInterrupt: quit() for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ try: m.read(i) debug('m read'); except ('SocketError', socket.error), err: if i != m: if i.msgqueue: nick = email2nick(i.emails[0]) dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) for msg in i.msgqueue: debug(msg ) m.close(i) else: debug('\nMain socket closed (%s)' % str(err)) quit(1) except 'XFRError', err: debug("\rXFR Error: %s" % str(err)) th = msn_wait(); th.start(); mySocket.listen(10) -conn, addr = mySocket.accept() while True: - data = conn.recv(10240) - if not data: - break - pcmd = parse_cmd(data) - if not pcmd: - conn.send('unkown!') - else: - if pcmd[0] == 'send': - email = pcmd[1] - msg = pcmd[2] - pstr = m.sendmsg(email, msg) - print pstr - conn.send('ok') - else: - conn.send(pcmd[0]) -conn.close() + try: + conn, addr = mySocket.accept() + data = conn.recv(10240) + if not data: + continue + msg = parse_cmd(data) + conn.send(msg) + conn.close() + except KeyboardInterrupt: + debug('ctrl + c') + quit() + except: + debug('Main has terminal') + quit(1) diff --git a/test.py b/test.py new file mode 100755 index 0000000..ce01c64 --- /dev/null +++ b/test.py @@ -0,0 +1,36 @@ +import sys, select, socket, time +HOST = '127.0.0.1' +PORT = 8888 + + +mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +try: + mySocket.bind((HOST, PORT)) +except socket.error: + sys.exit('call to bind fail') + +mySocket.listen(10) +(conn, addr) = mySocket.accept() +while True: + data = conn.recv(1024) + if not data: + break + conn.send(data) + + +#if fd: + #print fd[0] + #(clientsocket, address) = fd[0].accept() + #clientsocket.close() + +#conn, addr = mySocket.accept() +#while True: +# data = conn.recv(10240) +# if not data: +# break + +# conn.send(data) +#conn.close() + + +#socket.gethostname() \ No newline at end of file
wjzhangq/python-msn-bot
0472cbfb0a122a1eef5d732604a9dcde47bdf2ef
add listen port
diff --git a/README b/README old mode 100644 new mode 100755 diff --git a/msnbot.py b/msnbot.py index cd5765f..f00a87a 100755 --- a/msnbot.py +++ b/msnbot.py @@ -1,223 +1,272 @@ #!/usr/bin/evn ptyhon # -*- coding:utf-8 -*- import msnlib, msncb import sys, select, socket, time +import threading m = msnlib.msnd() m.cb = msncb.cb() m.encoding = 'utf-8' timeout = 300 m.email = '[email protected]' m.pwd = '123456' +HOST = '127.0.0.1' +PORT = 8888 def null(s): "Null function, useful to void debug ones" pass msnlib.debug = null msncb.debug = null def debug(str): print str + '' def now(): "Returns the current time, in tuple format" return time.localtime(time.time()) def quit(code = 0): "Exits" debug('Closing') try: try: m.disconnect() except: pass except: pass sys.exit(code) def nick2email(nick): "Returns an email according to the given nick, or None if noone matches" for email in m.users.keys(): if m.users[email].nick == nick: return email if nick in m.users.keys(): return nick return None def email2nick(email): "Returns a nick accoriding to the given email, or None if noone matches" if email in m.users.keys(): return m.users[email].nick else: return None # message def cb_msg(md, type, tid, params, sbd): t = tid.split(' ') email = t[0] # parse lines = params.split('\n') headers = {} eoh = 0 for i in lines: # end of headers if i == '\r': break tv = i.split(':', 1) type = tv[0] value = tv[1].strip() headers[type] = value eoh += 1 eoh +=1 # handle special hotmail messages if email == 'Hotmail': if not headers.has_key('Content-Type'): return hotmail_info = {} # parse the body for i in lines: i = i.strip() if not i: continue tv = i.split(':', 1) type = tv[0] value = tv[1].strip() hotmail_info[type] = value msnlib.debug(params) if headers['Content-Type'] == 'text/x-msmsgsinitialemailnotification; charset=UTF-8': newmsgs = int(hotmail_info['Inbox-Unread']) if not newmsgs: return debug('\rYou have %s unread email(s)' % str(newmsgs) \ + ' in your Hotmail account') elif headers['Content-Type'] == 'text/x-msmsgsemailnotification; charset=UTF-8': from_name = hotmail_info['From'] from_addr = hotmail_info['From-Addr'] subject = hotmail_info['Subject'] debug('\rYou have just received an email in your' + \ ' Hotmail account:') debug('\r\tFrom: %s (%s)' % (from_name, from_addr)) debug('\r\tSubject: %s' % subject) return if headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-msmsgscontrol': # the typing notices nick = email2nick(email) if not nick: nick = email if not m.users[email].priv.has_key('typing'): m.users[email].priv['typing'] = 0 if not m.users[email].priv['typing']: debug('\r') ctime = time.strftime('%I:%M:%S%p', now()) debug('%s ' % ctime) debug('%s' % nick) debug(' is typing') m.users[email].priv['typing'] = time.time() elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-clientcaps': # ignore the x-clientcaps messages generated from gaim pass elif headers.has_key('Content-Type') and headers['Content-Type'] == 'text/x-keepalive': # ignore kopete's keepalive messages pass else: # messages m.users[email].priv['typing'] = 0 - debug(email + '-*-' + '-*-'.join(lines)); + print(email) + print(lines) m.sendmsg(email, lines[-1]) msncb.cb_msg(md, type, tid, params, sbd) m.cb.msg = cb_msg # server errors def cb_err(md, errno, params): if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] desc = '\rServer sent error %d: %s' % (errno, desc) - perror(desc) + debug(desc) msncb.cb_err(md, errno, params) m.cb.err = cb_err # users add, delete and modify def cb_add(md, type, tid, params): t = params.split(' ') type = t[0] if type == 'RL' or type == 'FL': email = t[2] nick = urllib.unquote(t[3]) if type == 'RL': - out = '\r' + c.blue + c.bold + ('%s (%s) ' % (email, nick)) \ - + c.magenta + 'has added you to his contact list' + out = ('%s (%s) ' % (email, nick)) \ + + 'has added you to his contact list' debug(out) beep() elif type == 'FL': - out = '\r' + c.blue + c.bold + ('%s (%s) ' % (email, nick)) \ - + c.magenta + 'has been added to your contact list' + out = ('%s (%s) ' % (email, nick)) \ + + 'has been added to your contact list' debug(out) msncb.cb_add(md, type, tid, params) m.cb.add = cb_add +def parse_cmd(str): + data = str.split(':', 2) + if len(data) == 3: + return data + return None + + +mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +try: + mySocket.bind((HOST, PORT)) +except socket.error: + sys.exit('call to bind fail') + try: m.login() debug('login done') except 'AuthError', info: errno = int(info[0]) if not msncb.error_table.has_key(errno): desc = 'Unknown' else: desc = msncb.error_table[errno] debug('Error: %s (%s)' % (desc, errno)) quit(1) except KeyboardInterrupt: quit() except ('SocketError', socket.error), info: debug('Network error: ' + str(info)) quit(1) except: debug('Exception logging in') quit(1) # call sync to get the lists and refresh if m.sync(): debug('sync done') list_complete = 0 else: debug('Error syncing users') m.change_status('online'); -while True: - fds = m.pollable() - infd = fds[0] - outfd = fds[1] + +#muti threading +class msn_wait(threading.Thread): + def __init__(self): + threading.Thread.__init__(self, name='msn wait') - try: - fds = select.select(infd, outfd, [], timeout) - except KeyboardInterrupt: - quit() + def run(self): + global m + while True: + fds = m.pollable() + infd = fds[0] + outfd = fds[1] + + try: + fds = select.select(infd, outfd, [], timeout) + except KeyboardInterrupt: + quit() - for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ - try: - m.read(i) - debug('m read'); - except ('SocketError', socket.error), err: - if i != m: - if i.msgqueue: - nick = email2nick(i.emails[0]) - dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) - for msg in i.msgqueue: - debug(msg ) - m.close(i) - else: - debug('\nMain socket closed (%s)' % str(err)) - quit(1) - except 'XFRError', err: - debug("\rXFR Error: %s" % str(err)) + for i in fds[0] + fds[1]: # see msnlib.msnd.pollable.__doc__ + try: + m.read(i) + debug('m read'); + except ('SocketError', socket.error), err: + if i != m: + if i.msgqueue: + nick = email2nick(i.emails[0]) + dubeg("\rConnection with %s closed - the following messages couldn't be sent:" % (nick)) + for msg in i.msgqueue: + debug(msg ) + m.close(i) + else: + debug('\nMain socket closed (%s)' % str(err)) + quit(1) + except 'XFRError', err: + debug("\rXFR Error: %s" % str(err)) + +th = msn_wait(); +th.start(); + + +mySocket.listen(10) +conn, addr = mySocket.accept() +while True: + data = conn.recv(10240) + if not data: + break + pcmd = parse_cmd(data) + if not pcmd: + conn.send('unkown!') + else: + if pcmd[0] == 'send': + email = pcmd[1] + msg = pcmd[2] + pstr = m.sendmsg(email, msg) + print pstr + conn.send('ok') + else: + conn.send(pcmd[0]) +conn.close()
acvwilson/currency
2be66c6b52c3bfdf4be5a6853e90992671eaf3f5
Change Xe source to use the newer html format.
diff --git a/examples/xe1.rb b/examples/xe1.rb index f4b7abd..af76db0 100644 --- a/examples/xe1.rb +++ b/examples/xe1.rb @@ -1,20 +1,21 @@ $:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) +require 'rubygems' require 'currency' require 'currency/exchange/rate/source/xe' ex = Currency::Exchange::Rate::Source::Xe.new() Currency::Exchange::Rate::Source.current = ex puts ex.inspect puts ex.parse_page_rates.inspect usd = Currency.Money("1", 'USD') puts "usd = #{usd}" cad = usd.convert(:CAD) puts "cad = #{cad}" diff --git a/lib/currency/exchange/rate/source/xe.rb b/lib/currency/exchange/rate/source/xe.rb index 0163c04..72604bc 100644 --- a/lib/currency/exchange/rate/source/xe.rb +++ b/lib/currency/exchange/rate/source/xe.rb @@ -1,152 +1,144 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'currency/exchange/rate/source/base' require 'net/http' require 'open-uri' require 'hpricot' # Cant use REXML because of missing </form> tags -- 2007/03/11 # require 'rexml/document' # Connects to http://xe.com and parses "XE.com Quick Cross Rates" # from home page HTML. # class Currency::Exchange::Rate::Source::Xe < ::Currency::Exchange::Rate::Source::Provider # Defines the pivot currency for http://xe.com/. PIVOT_CURRENCY = :USD def initialize(*opt) self.uri = 'http://xe.com/' self.pivot_currency = PIVOT_CURRENCY @raw_rates = nil super(*opt) end # Returns 'xe.com'. def name 'xe.com' end def clear_rates @raw_rates = nil super end # Returns a cached Hash of rates: # # xe.raw_rates[:USD][:CAD] => 1.0134 # def raw_rates # Force load of rates @raw_rates ||= parse_page_rates end # Parses http://xe.com homepage HTML for # quick rates of 10 currencies. def parse_page_rates(data = nil) data = get_page_content unless data doc = Hpricot(data) # xe.com no longer gives date/time. # Remove usecs. time = Time.at(Time.new.to_i).getutc @rate_timestamp = time # parse out the currency names in the table - currency = [ ] - doc.search("table.currency tr:first-child .c1").each do |td| - currency.push(td.inner_text.strip.upcase.intern) - end + currency = doc.search("table.chart tr:first-child .flagtext").map {|td| td.inner_text.strip.upcase.intern} $stderr.puts "Found currencies: #{currency.inspect}" if @verbose raise ParserError, "Currencies header not found" if currency.empty? # Parse out the actual rates, dealing with the explanation gunk about which currency is worth more - parsed_rates = doc.search("table.currency tr:nth-child(0) .c2, table.currency tr:nth-child(0) .cLast").map do |e| - if (inner = e.search('div.aboveLayer')).size > 0 - inner.inner_text.strip - else - e.inner_text.strip - end - end + parsed_rates = doc.search("table.chart tr:nth-child(2) td a")[2..-1].map {|n| n.inner_text} + parsed_rates = ["1.00"] + parsed_rates.values_at(* parsed_rates.each_index.select {|i| i.even?}) rate = { } parsed_rates.each_with_index do |parsed_rate, i| usd_to_cur = parsed_rate.to_f cur = currency[i] raise ParserError, "Currency not found at column #{i}" unless cur next if cur.to_s == PIVOT_CURRENCY.to_s (rate[PIVOT_CURRENCY] ||= {})[cur] = usd_to_cur (rate[cur] ||= { })[PIVOT_CURRENCY] ||= 1.0 / usd_to_cur $stderr.puts "#{cur.inspect} => #{usd_to_cur}" if @verbose end raise ::Currency::Exception::UnavailableRates, "No rates found in #{get_uri.inspect}" if rate.keys.empty? raise ParserError, [ "Not all currencies found", :expected_currences, currency, :found_currencies, rate.keys, :missing_currencies, currency - rate.keys, ] if rate.keys.size != currency.size @lines = @line = nil raise ParserError, "Rate date not found" unless @rate_timestamp rate end def eat_lines_until(rx) until @lines.empty? @line = @lines.shift if md = rx.match(@line) $stderr.puts "\nMATCHED #{@line.inspect} WITH #{rx.inspect} AT LINES:\n#{@lines[0..4].inspect}" if @verbose return md end yield @line if block_given? end raise ParserError, [ 'eat_lines_until failed', :rx, rx ] false end # Return a list of known base rates. def load_rates(time = nil) if time $stderr.puts "#{self}: WARNING CANNOT SUPPLY HISTORICAL RATES" unless @time_warning @time_warning = true end rates = raw_rates # Load rates rates_pivot = rates[PIVOT_CURRENCY] raise ::Currency::Exception::UnknownRate, [ "Cannot get base rate #{PIVOT_CURRENCY.inspect}", :pivot_currency, PIVOT_CURRENCY, ] unless rates_pivot result = rates_pivot.keys.collect do | c2 | new_rate(PIVOT_CURRENCY, c2, rates_pivot[c2], @rate_timestamp) end result end end # class
acvwilson/currency
d2bda0ae54ad6d10f9a4d960c4e1039e2d8789b3
bump version no. so github maybe builds gem?
diff --git a/currency.gemspec b/currency.gemspec index e427cad..27400a8 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| s.name = %q{currency} - s.version = "0.7.0.1" + s.version = "0.7.0.11" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson", "David Palm"] s.date = %q{#{Date.today}} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]", "[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} s.summary = %q{#{s.name} #{s.version}} end
acvwilson/currency
d106f09606e62ab90862e118e0b1e248d9c92334
Quick and dirty fix to XE.com change - introduces a denpendancy on hpricot. But it works
diff --git a/lib/currency/exchange/rate/source/xe.rb b/lib/currency/exchange/rate/source/xe.rb index 609a9d1..0163c04 100644 --- a/lib/currency/exchange/rate/source/xe.rb +++ b/lib/currency/exchange/rate/source/xe.rb @@ -1,165 +1,152 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'currency/exchange/rate/source/base' require 'net/http' require 'open-uri' +require 'hpricot' # Cant use REXML because of missing </form> tags -- 2007/03/11 # require 'rexml/document' # Connects to http://xe.com and parses "XE.com Quick Cross Rates" # from home page HTML. # class Currency::Exchange::Rate::Source::Xe < ::Currency::Exchange::Rate::Source::Provider # Defines the pivot currency for http://xe.com/. PIVOT_CURRENCY = :USD def initialize(*opt) self.uri = 'http://xe.com/' self.pivot_currency = PIVOT_CURRENCY @raw_rates = nil super(*opt) end # Returns 'xe.com'. def name 'xe.com' end def clear_rates @raw_rates = nil super end # Returns a cached Hash of rates: # # xe.raw_rates[:USD][:CAD] => 1.0134 # def raw_rates # Force load of rates @raw_rates ||= parse_page_rates end # Parses http://xe.com homepage HTML for # quick rates of 10 currencies. def parse_page_rates(data = nil) data = get_page_content unless data - @lines = data = data.split(/\n/); - - # xe.com no longer gives date/time. - # Remove usecs. - time = Time.at(Time.new.to_i).getutc - @rate_timestamp = time - - eat_lines_until /More currencies\.\.\.<\/a>/i - eat_lines_until /^\s*<tr>/i - eat_lines_until /^\s*<tr>/i - - # Read first table row to get position for each currency - currency = [ ] - eat_lines_until /^\s*<\/tr>/i do - if md = /<td[^>]+?>.*?\/> ([A-Z][A-Z][A-Z])<\/td>/.match(@line) - cur = md[1].intern - cur_i = currency.size - currency.push(cur) - $stderr.puts "Found currency header: #{cur.inspect} at #{cur_i}" if @verbose - end - end - raise ParserError, "Currencies header not found" if currency.empty? - - - # Skip until "1 USD =" - eat_lines_until /^\s*<td[^>]+?> 1&nbsp;+USD&nbsp;=/ - - # Read first row of 1 USD = ... - rate = { } - cur_i = -1 - eat_lines_until /^\s*<\/tr>/i do - # Grok: - # - # <td align="center" class="cur2 currencyA">114.676</td>\n - # - # AND - # - # <td align="center" class="cur2 currencyA"><div id="positionImage">0.9502\n - # - if md = /<td[^>]+?>\s*(<div[^>]+?>\s*)?(\d+\.\d+)\s*(<\/td>)?/i.match(@line) - usd_to_cur = md[2].to_f - cur_i = cur_i + 1 - cur = currency[cur_i] - raise ParserError, "Currency not found at column #{cur_i}" unless cur - next if cur.to_s == PIVOT_CURRENCY.to_s - (rate[PIVOT_CURRENCY] ||= {})[cur] = usd_to_cur - (rate[cur] ||= { })[PIVOT_CURRENCY] ||= 1.0 / usd_to_cur - $stderr.puts "#{cur.inspect} => #{usd_to_cur}" if @verbose - end - end + doc = Hpricot(data) + + # xe.com no longer gives date/time. + # Remove usecs. + + time = Time.at(Time.new.to_i).getutc + @rate_timestamp = time + + # parse out the currency names in the table + currency = [ ] + doc.search("table.currency tr:first-child .c1").each do |td| + currency.push(td.inner_text.strip.upcase.intern) + end + $stderr.puts "Found currencies: #{currency.inspect}" if @verbose + raise ParserError, "Currencies header not found" if currency.empty? + + # Parse out the actual rates, dealing with the explanation gunk about which currency is worth more + parsed_rates = doc.search("table.currency tr:nth-child(0) .c2, table.currency tr:nth-child(0) .cLast").map do |e| + if (inner = e.search('div.aboveLayer')).size > 0 + inner.inner_text.strip + else + e.inner_text.strip + end + end + + rate = { } + + parsed_rates.each_with_index do |parsed_rate, i| + usd_to_cur = parsed_rate.to_f + cur = currency[i] + raise ParserError, "Currency not found at column #{i}" unless cur + next if cur.to_s == PIVOT_CURRENCY.to_s + (rate[PIVOT_CURRENCY] ||= {})[cur] = usd_to_cur + (rate[cur] ||= { })[PIVOT_CURRENCY] ||= 1.0 / usd_to_cur + $stderr.puts "#{cur.inspect} => #{usd_to_cur}" if @verbose + end raise ::Currency::Exception::UnavailableRates, "No rates found in #{get_uri.inspect}" if rate.keys.empty? raise ParserError, [ "Not all currencies found", :expected_currences, currency, :found_currencies, rate.keys, :missing_currencies, currency - rate.keys, ] if rate.keys.size != currency.size @lines = @line = nil raise ParserError, "Rate date not found" unless @rate_timestamp rate end def eat_lines_until(rx) until @lines.empty? @line = @lines.shift if md = rx.match(@line) $stderr.puts "\nMATCHED #{@line.inspect} WITH #{rx.inspect} AT LINES:\n#{@lines[0..4].inspect}" if @verbose return md end yield @line if block_given? end raise ParserError, [ 'eat_lines_until failed', :rx, rx ] false end # Return a list of known base rates. def load_rates(time = nil) if time $stderr.puts "#{self}: WARNING CANNOT SUPPLY HISTORICAL RATES" unless @time_warning @time_warning = true end rates = raw_rates # Load rates rates_pivot = rates[PIVOT_CURRENCY] raise ::Currency::Exception::UnknownRate, [ "Cannot get base rate #{PIVOT_CURRENCY.inspect}", :pivot_currency, PIVOT_CURRENCY, ] unless rates_pivot result = rates_pivot.keys.collect do | c2 | new_rate(PIVOT_CURRENCY, c2, rates_pivot[c2], @rate_timestamp) end result end end # class
acvwilson/currency
dd38d6d09c7496e85dad363e358d0cad1c48b846
Fixed broken gemspec
diff --git a/currency.gemspec b/currency.gemspec index cda3a26..e427cad 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| s.name = %q{currency} - s.version = "0.7" + s.version = "0.7.0.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson", "David Palm"] s.date = %q{#{Date.today}} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]", "[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] - s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] + s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} s.summary = %q{#{s.name} #{s.version}} end
acvwilson/currency
912ab7d6e5cb229a348abf0dbdbb43d91776afc3
Bumped version to 0.7
diff --git a/currency.gemspec b/currency.gemspec index 3a01ceb..cda3a26 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| s.name = %q{currency} - s.version = "0.6.4" + s.version = "0.7" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson", "David Palm"] s.date = %q{#{Date.today}} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]", "[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} s.summary = %q{#{s.name} #{s.version}} end
acvwilson/currency
3a760ad26f6a3012cdc2094a22d0f165384d207e
.gitignor'ing gemfiles
diff --git a/.gitignore b/.gitignore index da7a78e..ac47971 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -spec/debug.log \ No newline at end of file +spec/debug.log +*.gem \ No newline at end of file
acvwilson/currency
42541c1cc40eda99f796ddc7e9b0f7f31ab425c5
Finally! An almost-sane AR spec'ing environment, with test data, spec helper and migrations Added first timid AR specs. More needed, more to come, but it's a start Added a currency_column setter that resets the money attribute ivar, thus forcing a re-init at next read (fixes a bug when using update_attributes) Removed debugging code Removed unnecessary setting and casting of currency_column alias_accessor localized to where it's being set Code cleanup
diff --git a/lib/currency/active_record.rb b/lib/currency/active_record.rb index 5658767..a846bbf 100644 --- a/lib/currency/active_record.rb +++ b/lib/currency/active_record.rb @@ -1,298 +1,304 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'active_record/base' require File.join(File.dirname(__FILE__), '..', 'currency') # See Currency::ActiveRecord::ClassMethods class ActiveRecord::Base @@money_attributes = { } # Called by money macro when a money attribute # is created. def self.register_money_attribute(attr_opts) (@@money_attributes[attr_opts[:class]] ||= { })[attr_opts[:attr_name]] = attr_opts end # Returns an array of option hashes for all the money attributes of # this class. # # Superclass attributes are not included. def self.money_attributes_for_class(cls) (@@money_atttributes[cls] || { }).values end # Iterates through all known money attributes in all classes. # # each_money_attribute { | money_opts | # ... # } def self.each_money_attribute(&blk) @@money_attributes.each do | cls, hash | hash.each do | attr_name, attr_opts | yield attr_opts end end end end # class # See Currency::ActiveRecord::ClassMethods module Currency::ActiveRecord def self.append_features(base) # :nodoc: # $stderr.puts " Currency::ActiveRecord#append_features(#{base})" super base.extend(ClassMethods) end # == ActiveRecord Suppport # # Support for Money attributes in ActiveRecord::Base subclasses: # # require 'currency' # require 'currency/active_record' # # class Entry < ActiveRecord::Base # attr_money :amount # end # module ClassMethods # Deprecated: use attr_money. def money(*args) $stderr.puts "WARNING: money(#{args.inspect}) deprecated, use attr_money: in #{caller(1)[0]}" attr_money(*args) end # Defines a Money object attribute that is bound # to a database column. The database column to store the # Money value representation is assumed to be # INTEGER and will store Money#rep values. # # Options: # # :column => undef # # Defines the column to use for storing the money value. # Defaults to the attribute name. # # If this column is different from the attribute name, # the money object will intercept column=(x) to flush # any cached Money object. # # :currency => currency_code (e.g.: :USD) # # Defines the Currency to use for storing a normalized Money # value. # # All Money values will be converted to this Currency before # storing. This allows SQL summary operations, # like SUM(), MAX(), AVG(), etc., to produce meaningful results, # regardless of the initial currency specified. If this # option is used, subsequent reads will be in the specified # normalization :currency. # # :currency_column => undef # # Defines the name of the CHAR(3) column used to store and # retrieve the Money's Currency code. If this option is used, each # record may use a different Currency to store the result, such # that SQL summary operations, like SUM(), MAX(), AVG(), # may return meaningless results. # # :currency_preferred_column => undef # # Defines the name of a CHAR(3) column used to store and # retrieve the Money's Currency code. This option can be used # with normalized Money values to retrieve the Money value # in its original Currency, while # allowing SQL summary operations on the normalized Money values # to still be valid. # # :time => undef # # Defines the name of attribute used to # retrieve the Money's time. If this option is used, each # Money value will use this attribute during historical Currency # conversions. # # Money values can share a time value with other attributes # (e.g. a created_on column). # # If this option is true, the money time attribute will be named # "#{attr_name}_time" and :time_update will be true. # # :time_update => undef # # If true, the Money time value is updated upon setting the # money attribute. # def attr_money(attr_name, *opts) opts = Hash[*opts] attr_name = attr_name.to_s opts[:class] = self opts[:table] = self.table_name opts[:attr_name] = attr_name.to_sym ::ActiveRecord::Base.register_money_attribute(opts) column = opts[:column] || opts[:attr_name] opts[:column] = column + # TODO: rewrite with define_method (dvd, 15-03-2009) if column.to_s != attr_name.to_s alias_accessor = <<-"end_eval" -alias :before_money_#{column}=, :#{column}= - -def #{column}=(__value) - @{attr_name} = nil # uncache - before_money#{column} = __value -end + alias :before_money_#{column}=, :#{column}= + def #{column}=(__value) + @{attr_name} = nil # uncache + before_money#{column} = __value + end end_eval - end + end + alias_accessor ||= '' + currency = opts[:currency] currency_column = opts[:currency_column] if currency_column && ! currency_column.kind_of?(String) - currency_column = currency_column.to_s currency_column = "#{column}_currency" end + if currency_column - read_currency = "read_attribute(:#{currency_column.to_s})" + read_currency = "read_attribute(:#{currency_column})" write_currency = "write_attribute(:#{currency_column}, #{attr_name}_money.nil? ? nil : #{attr_name}_money.currency.code.to_s)" end opts[:currency_column] = currency_column currency_preferred_column = opts[:currency_preferred_column] if currency_preferred_column currency_preferred_column = currency_preferred_column.to_s read_preferred_currency = "@#{attr_name} = @#{attr_name}.convert(read_attribute(:#{currency_preferred_column}))" write_preferred_currency = "write_attribute(:#{currency_preferred_column}, @#{attr_name}_money.currency.code)" end time = opts[:time] write_time = '' if time if time == true time = "#{attr_name}_time" opts[:time_update] = true end read_time = "self.#{time}" end opts[:time] = time + if opts[:time_update] write_time = "self.#{time} = #{attr_name}_money && #{attr_name}_money.time" end currency ||= ':USD' time ||= 'nil' read_currency ||= currency read_time ||= time money_rep ||= "#{attr_name}_money.rep" validate_allow_nil = opts[:allow_nil] ? ', :allow_nil => true' : '' validate = "# Validation\n" - validate << "\nvalidates_numericality_of :#{attr_name}#{validate_allow_nil}\n" + validate << "\nvalidates_numericality_of :#{attr_name} #{validate_allow_nil}\n" validate << "\nvalidates_format_of :#{currency_column}, :with => /^[A-Z][A-Z][A-Z]$/#{validate_allow_nil}\n" if currency_column - # validate << "\nbefore_validation :debug_#{attr_name}_before_validate\n" - # - # validate << %Q{ - # def debug_#{attr_name}_before_validate - # logger.debug "\tValidating #{attr_name}. Allow nils? #{validate_allow_nil}" - # logger.debug "\t\t'#{attr_name}': '\#\{#{attr_name}.inspect\}' (class: '\#\{#{attr_name}.class\}')" - # logger.debug "\t\tcurrency column, '#{currency_column}': '\#\{#{currency_column}.inspect\}' (class: '\#\{#{currency_column}.class\}'), matches '/^[A-Z][A-Z][A-Z]$/': \#\{'#{currency_column}'.match(/^[A-Z][A-Z][A-Z]$/).to_a.inspect\}" - # end - # } - - alias_accessor ||= '' - - module_eval (opts[:module_eval] = x = <<-"end_eval"), __FILE__, __LINE__ -#{validate} - -#{alias_accessor} - -def #{attr_name} - # $stderr.puts " \#{self.class.name}##{attr_name}" - unless @#{attr_name} - #{attr_name}_rep = read_attribute(:#{column}) - unless #{attr_name}_rep.nil? - @#{attr_name} = ::Currency::Money.new_rep(#{attr_name}_rep, #{read_currency} || #{currency}, #{read_time} || #{time}) - #{read_preferred_currency} - end - end - @#{attr_name} -end - -def #{attr_name}=(value) - if value.nil? || value.to_s.strip == '' - #{attr_name}_money = nil - elsif value.kind_of?(Integer) || value.kind_of?(String) || value.kind_of?(Float) - #{attr_name}_money = ::Currency::Money(value, #{currency}) - #{write_preferred_currency} - elsif value.kind_of?(::Currency::Money) - #{attr_name}_money = value - #{write_preferred_currency} - #{write_currency ? write_currency : "#{attr_name}_money = #{attr_name}_money.convert(#{currency})"} - else - raise ::Currency::Exception::InvalidMoneyValue, value - end - - @#{attr_name} = #{attr_name}_money # TODO: Really needed? Isn't the write_attribute enough? + + # ================================================================================================= + # = Define the currency_column setter, so that the Money object changes when the currency changes = + # ================================================================================================= + if currency_column + currency_column_setter = %Q{ + def #{currency_column}=(currency_code) + @#{attr_name} = nil + write_attribute(:#{currency_column}, currency_code) + end + } + class_eval currency_column_setter, __FILE__, __LINE__ + end + + class_eval (opts[:module_eval] = x = <<-"end_eval"), __FILE__, __LINE__ + #{validate} + + #{alias_accessor} + + # Getter + def #{attr_name} + unless @#{attr_name} + rep = read_attribute(:#{column}) + unless rep.nil? + @#{attr_name} = ::Currency::Money.new_rep(rep, #{read_currency} || #{currency}, #{read_time} || #{time}) + #{read_preferred_currency} + end + end + @#{attr_name} + end + + # Setter + def #{attr_name}=(value) + if value.nil? || value.to_s.strip == '' + #{attr_name}_money = nil + elsif value.kind_of?(Integer) || value.kind_of?(String) || value.kind_of?(Float) + #{attr_name}_money = ::Currency::Money(value, #{read_currency}) + #{write_preferred_currency} + elsif value.kind_of?(::Currency::Money) + #{attr_name}_money = value + #{write_preferred_currency} + #{write_currency ? write_currency : "#{attr_name}_money = #{attr_name}_money.convert(#{currency})"} + else + raise ::Currency::Exception::InvalidMoneyValue, value + end + + @#{attr_name} = #{attr_name}_money # TODO: Really needed? Isn't the write_attribute enough? (answer: no, because the getter method does an "if @#{attr_name}" to check if it's set) - write_attribute(:#{column}, #{attr_name}_money.nil? ? nil : #{money_rep}) - #{write_time} + write_attribute(:#{column}, #{attr_name}_money.nil? ? nil : #{attr_name}_money.rep) + #{write_time} - value -end - -def #{attr_name}_before_type_cast - #{attr_name}.to_f if #{attr_name} -end + value + end + def #{attr_name}_before_type_cast + #{attr_name}.to_f if #{attr_name} + end + end_eval =begin Replaced the _before_type_cast because it's buggy and weird: Bug: if the Currency::Formatter.default is set to include the currency code (:code => true) then the call below to format() will leave the code in. When the validates_numericality_of kicks in it can't cast to Float (yes, validates_numericality_of basically does just that) because of the "USD" of the currency code and everything fails. All the time. Weird: assigning to "x" doesn't really make any sense, just useless overhead. Using the rare &&= is not a big win over something like: x && x.format(..., ...) and actually longer too. The intention of the _before_type_cast method is to return a raw, unformatted value. When it does work, it returns a string on the form "123.456". Why not cast to Float right away? Arguably, the "raw" currency value is the integer rep stored in the db, but that wouldn't work very well with any known rails validations. I think casting to Float is reasonable. The taste Kurt Stephens has for weird Ruby code never ceases to amaze me. :) (dvd, 05-02-2009) def #{attr_name}_before_type_cast # FIXME: User cannot specify Currency x = #{attr_name} x &&= x.format(:symbol => false, :currency => false, :thousands => false) x end =end # $stderr.puts " CODE = #{x}" end end end ActiveRecord::Base.class_eval do include Currency::ActiveRecord end diff --git a/spec/ar_simple_spec.rb b/spec/ar_simple_spec.rb index da5e868..495d4bd 100644 --- a/spec/ar_simple_spec.rb +++ b/spec/ar_simple_spec.rb @@ -1,23 +1,80 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # Copyright (C) 2008 Asa Wilson <acvwilson(at)gmail.com> +# Copyright (C) 2009 David Palm <dvdplm(at)gmail.com> # See LICENSE.txt for details. require File.dirname(__FILE__) + '/ar_spec_helper' -describe Currency::ActiveRecord do - it "simple" do - # TODO: move insert_records into a before block? - insert_records +class Dog < ActiveRecord::Base + attr_money :price, :currency_column => true, :allow_nil => true +end - usd = @currency_test.find(@usd.id) - usd.should_not be_nil - assert_equal_currency usd, @usd +describe "extending ActiveRecord" do + describe "attr_money" do + before do + Dog.connection.execute("INSERT INTO dogs VALUES(null, 'fido', 1500, 'USD')") # NOTE: by-passing AR here to achieve clean slate (dvd, 15-03-2009) + @dog = Dog.first + end - cad = @currency_test.find(@cad.id) - cad.should_not == nil - assert_equal_money cad, @cad + describe "retrieving money values" do + it "sets up the Money object at first read" do + pending + end + + it "returns the ivar on subsequent reads" do + pending + end + + it "does not setup a Money object if the db column does not contain an integer to use for money rep" do + pending + end + + it "casts the currency to the preferred one, if a preferred currency was set" do + pending + end + end + + describe "currency column" do + before do + Dog.connection.execute("INSERT INTO dogs VALUES(null, 'fido', 1500, 'USD')") # NOTE: by-passing AR here to achieve clean slate (dvd, 15-03-2009) + @dog = Dog.first + end - cad.amount.currency.code.should == :USD - end -end + it "changes the currency when the value on the currency column changes" do + @dog.price.currency.code.should == :USD + @dog.update_attributes(:price_currency => 'EUR') + @dog.price.currency.code.should == :EUR + end + + it "does NOT convert to the new currency when the currency column changes" do + @dog.price.rep.should == 1500 + @dog.update_attributes(:price_currency => :EUR) + @dog.price.rep.should == 1500 + end + end + + describe "saving" do + it "saves the price with the default currency when set to 10.money" do + @dog.price = 10.money + @dog.price.should == Currency::Money("10") + end + + it "saves the price with the currency of the Money object" do + @dog.price = 10.money(:EUR) + @dog.price.should == Currency::Money("10", "EUR") + end + + it "can change just the currency" do + @dog.price_currency = 'CAD' + @dog.save + @dog.price.should == Currency::Money("15", "CAD") + end + + it "can save changes using update_attributes" do + @dog.update_attributes(:price => 5, :price_currency => 'CAD') + @dog.price.should == 5.money('CAD') + end + end + end +end \ No newline at end of file diff --git a/spec/ar_spec_helper.rb b/spec/ar_spec_helper.rb index 086adfd..483cc0d 100644 --- a/spec/ar_spec_helper.rb +++ b/spec/ar_spec_helper.rb @@ -1,127 +1,164 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # Copyright (C) 2008 Asa Wilson <acvwilson(at)gmail.com> # See LICENSE.txt for details. require File.dirname(__FILE__) + '/spec_helper' require 'active_record' require 'active_record/migration' require File.dirname(__FILE__) + '/../lib/currency/active_record' +config = YAML::load(IO.read(File.dirname(__FILE__) + '/db/database.yml')) +ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") +# ActiveRecord::Base.establish_connection(config['mysql_debug']) +ActiveRecord::Base.establish_connection(config['sqlite3mem']) + +ActiveRecord::Migration.verbose = false +load(File.dirname(__FILE__) + "/db/schema.rb") + +# ============================================ +# = Load some currency symbols (171 records) = +# ============================================ +currency_codes = IO.read(File.dirname(__FILE__) + '/db/currency_codes.sql') +currency_codes.each_line do |sql_insert| + ActiveRecord::Base.connection.execute(sql_insert) +end + +# ================================ +# = Load some rates (84 records) = +# ================================ +rates = IO.read(File.dirname(__FILE__) + '/db/currency_historical_rates.sql') +rates.each_line do |sql_insert| + ActiveRecord::Base.connection.execute(sql_insert) +end + +AR_M = ActiveRecord::Migration +AR_B = ActiveRecord::Base + + + +=begin +require File.dirname(__FILE__) + '/spec_helper' + +require 'active_record' +require 'active_record/migration' +require File.dirname(__FILE__) + '/../lib/currency/active_record' + AR_M = ActiveRecord::Migration AR_B = ActiveRecord::Base def ar_setup AR_B.establish_connection(database_spec) # Subclasses can override this. @currency_test_migration ||= nil @currency_test ||= nil # schema_down schema_up end # DB Connection info def database_spec # TODO: Get from ../config/database.yml:test # Create test database on: # MYSQL: # # sudo mysqladmin create test; # sudo mysql # grant all on test.* to test@localhost identified by 'test'; # flush privileges; # POSTGRES: # # CREATE USER test PASSWORD 'test'; # CREATE DATABASE test WITH OWNER = test; # # @database_spec = { # :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', # :host => ENV['TEST_DB_HOST'] || 'localhost', # :username => ENV['TEST_DB_USER'] || 'test', # :password => ENV['TEST_DB_PASS'] || 'test', # :database => ENV['TEST_DB_TEST'] || 'test' # } @database_spec = { :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', :host => ENV['TEST_DB_HOST'] || 'localhost', :username => ENV['TEST_DB_USER'] || 'root', :password => ENV['TEST_DB_PASS'] || '', :database => ENV['TEST_DB_TEST'] || 'currency_gem_test' } end # Run AR migrations UP def schema_up return unless @currency_test_migration begin @currency_test_migration.migrate(:up) rescue Object =>e $stderr.puts "Warning: #{e}" end end # Run AR migrations DOWN def schema_down return unless @currency_test_migration begin @currency_test_migration.migrate(:down) rescue Object => e $stderr.puts "Warning: #{e}" end end # Scaffold: insert stuff into DB so we can test AR integration def insert_records delete_records @currency_test.reset_column_information @usd = @currency_test.new(:name => '#1: USD', :amount => Currency::Money.new("12.34", :USD)) @usd.save @cad = @currency_test.new(:name => '#2: CAD', :amount => Currency::Money.new("56.78", :CAD)) @cad.save end def delete_records @currency_test.destroy_all end ################################################## # TODO: need this? def assert_equal_money(a,b) a.should_not be_nil b.should_not be_nil # Make sure a and b are not the same object. b.object_id.should_not == a.object_id b.id.should == a.id a.amount.should_not == nil a.amount.should be_kind_of(Currency::Money) b.amount.should_not == nil b.amount.should be_kind_of(Currency::Money) # Make sure that what gets stored in the database comes back out # when converted back to the original currency. b.amount.rep.should == a.amount.convert(b.amount.currency).rep end # TODO: need this? def assert_equal_currency(a,b) assert_equal_money a, b b.amount.rep.should == a.amount.rep b.amount.currency.should == a.amount.currency b.amount.currency.code.should == a.amount.currency.code -end \ No newline at end of file +end +=end \ No newline at end of file
acvwilson/currency
d6f70c91fd48d233edf2a3734a2643afee2f7fcf
gitignore ignores debug.log
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..da7a78e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +spec/debug.log \ No newline at end of file
acvwilson/currency
4db93fcb091f328f1f66fc88cd8c7c4237e6c71f
removed useless comments
diff --git a/spec/db/currency_historical_rates.sql b/spec/db/currency_historical_rates.sql index 46d71e8..0daee5a 100644 --- a/spec/db/currency_historical_rates.sql +++ b/spec/db/currency_historical_rates.sql @@ -1,84 +1,84 @@ -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (1,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','INR','xe.com-paid xml feed',48.7792,48.7792,1,48.7792,48.7792,48.7792,48.7792,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (2,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','EUR','xe.com-paid xml feed',0.798634,0.798634,1,0.798634,0.798634,0.798634,0.798634,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (3,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','AUD','xe.com-paid xml feed',1.56747,1.56747,1,1.56747,1.56747,1.56747,1.56747,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (4,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','GBP','xe.com-paid xml feed',0.682187,0.682187,1,0.682187,0.682187,0.682187,0.682187,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (5,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','CAD','xe.com-paid xml feed',1.24183,1.24183,1,1.24183,1.24183,1.24183,1.24183,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (6,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','BBD','xe.com-paid xml feed',1.995,1.995,1,1.995,1.995,1.995,1.995,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (7,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','USD','xe.com-paid xml feed',0.0205006,0.0205006,1,0.0205006,0.0205006,0.0205006,0.0205006,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDINR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (8,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','EUR','xe.com-paid xml feed',0.0163724,0.0163724,1,0.0163724,0.0163724,0.0163724,0.0163724,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDEUR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (9,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','AUD','xe.com-paid xml feed',0.032134,0.032134,1,0.032134,0.032134,0.032134,0.032134,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDAUD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (10,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','GBP','xe.com-paid xml feed',0.0139852,0.0139852,1,0.0139852,0.0139852,0.0139852,0.0139852,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (11,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','CAD','xe.com-paid xml feed',0.0254582,0.0254582,1,0.0254582,0.0254582,0.0254582,0.0254582,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDCAD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (12,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','BBD','xe.com-paid xml feed',0.0408986,0.0408986,1,0.0408986,0.0408986,0.0408986,0.0408986,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (13,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','USD','xe.com-paid xml feed',1.25214,1.25214,1,1.25214,1.25214,1.25214,1.25214,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDEUR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (14,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','INR','xe.com-paid xml feed',61.0783,61.0783,1,61.0783,61.0783,61.0783,61.0783,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDEUR))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (15,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','AUD','xe.com-paid xml feed',1.96269,1.96269,1,1.96269,1.96269,1.96269,1.96269,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDAUD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (16,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','GBP','xe.com-paid xml feed',0.854193,0.854193,1,0.854193,0.854193,0.854193,0.854193,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (17,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','CAD','xe.com-paid xml feed',1.55494,1.55494,1,1.55494,1.55494,1.55494,1.55494,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDCAD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (18,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','BBD','xe.com-paid xml feed',2.49802,2.49802,1,2.49802,2.49802,2.49802,2.49802,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (19,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','USD','xe.com-paid xml feed',0.637971,0.637971,1,0.637971,0.637971,0.637971,0.637971,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDAUD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (20,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','INR','xe.com-paid xml feed',31.1197,31.1197,1,31.1197,31.1197,31.1197,31.1197,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDAUD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (21,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','EUR','xe.com-paid xml feed',0.509505,0.509505,1,0.509505,0.509505,0.509505,0.509505,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDAUD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (22,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','GBP','xe.com-paid xml feed',0.435216,0.435216,1,0.435216,0.435216,0.435216,0.435216,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (23,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','CAD','xe.com-paid xml feed',0.792251,0.792251,1,0.792251,0.792251,0.792251,0.792251,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDCAD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (24,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','BBD','xe.com-paid xml feed',1.27275,1.27275,1,1.27275,1.27275,1.27275,1.27275,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (25,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','USD','xe.com-paid xml feed',1.46587,1.46587,1,1.46587,1.46587,1.46587,1.46587,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (26,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','INR','xe.com-paid xml feed',71.5041,71.5041,1,71.5041,71.5041,71.5041,71.5041,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDGBP))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (27,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','EUR','xe.com-paid xml feed',1.1707,1.1707,1,1.1707,1.1707,1.1707,1.1707,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDGBP))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (28,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','AUD','xe.com-paid xml feed',2.29771,2.29771,1,2.29771,2.29771,2.29771,2.29771,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDGBP))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (29,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','CAD','xe.com-paid xml feed',1.82036,1.82036,1,1.82036,1.82036,1.82036,1.82036,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDGBP),USDCAD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (30,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','BBD','xe.com-paid xml feed',2.92442,2.92442,1,2.92442,2.92442,2.92442,2.92442,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDGBP),USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (31,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','USD','xe.com-paid xml feed',0.805263,0.805263,1,0.805263,0.805263,0.805263,0.805263,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDCAD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (32,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','INR','xe.com-paid xml feed',39.2801,39.2801,1,39.2801,39.2801,39.2801,39.2801,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDCAD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (33,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','EUR','xe.com-paid xml feed',0.64311,0.64311,1,0.64311,0.64311,0.64311,0.64311,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDCAD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (34,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','AUD','xe.com-paid xml feed',1.26223,1.26223,1,1.26223,1.26223,1.26223,1.26223,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDCAD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (35,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','GBP','xe.com-paid xml feed',0.54934,0.54934,1,0.54934,0.54934,0.54934,0.54934,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDCAD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (36,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','BBD','xe.com-paid xml feed',1.6065,1.6065,1,1.6065,1.6065,1.6065,1.6065,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDCAD),USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (37,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','USD','xe.com-paid xml feed',0.501253,0.501253,1,0.501253,0.501253,0.501253,0.501253,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (38,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','INR','xe.com-paid xml feed',24.4507,24.4507,1,24.4507,24.4507,24.4507,24.4507,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDBBD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (39,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','EUR','xe.com-paid xml feed',0.400318,0.400318,1,0.400318,0.400318,0.400318,0.400318,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDBBD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (40,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','AUD','xe.com-paid xml feed',0.785699,0.785699,1,0.785699,0.785699,0.785699,0.785699,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDBBD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (41,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','GBP','xe.com-paid xml feed',0.341949,0.341949,1,0.341949,0.341949,0.341949,0.341949,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDBBD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (42,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','CAD','xe.com-paid xml feed',0.622471,0.622471,1,0.622471,0.622471,0.622471,0.622471,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDBBD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (43,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','AUD','xe.com-paid xml feed',1.54132,1.54132,1,1.54132,1.54132,1.54132,1.54132,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (44,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','CAD','xe.com-paid xml feed',1.23269,1.23269,1,1.23269,1.23269,1.23269,1.23269,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (45,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','BBD','xe.com-paid xml feed',2,2,1,2,2,2,2,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (46,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','INR','xe.com-paid xml feed',48.1826,48.1826,1,48.1826,48.1826,48.1826,48.1826,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (47,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','GBP','xe.com-paid xml feed',0.69295,0.69295,1,0.69295,0.69295,0.69295,0.69295,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (48,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','EUR','xe.com-paid xml feed',0.768573,0.768573,1,0.768573,0.768573,0.768573,0.768573,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (49,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','USD','xe.com-paid xml feed',0.648794,0.648794,1,0.648794,0.648794,0.648794,0.648794,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDAUD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (50,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','CAD','xe.com-paid xml feed',0.799762,0.799762,1,0.799762,0.799762,0.799762,0.799762,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDCAD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (51,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','BBD','xe.com-paid xml feed',1.29759,1.29759,1,1.29759,1.29759,1.29759,1.29759,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (52,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','INR','xe.com-paid xml feed',31.2606,31.2606,1,31.2606,31.2606,31.2606,31.2606,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDINR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (53,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','GBP','xe.com-paid xml feed',0.449582,0.449582,1,0.449582,0.449582,0.449582,0.449582,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (54,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','EUR','xe.com-paid xml feed',0.498646,0.498646,1,0.498646,0.498646,0.498646,0.498646,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDEUR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (55,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','USD','xe.com-paid xml feed',0.811234,0.811234,1,0.811234,0.811234,0.811234,0.811234,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDCAD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (56,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','AUD','xe.com-paid xml feed',1.25037,1.25037,1,1.25037,1.25037,1.25037,1.25037,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDCAD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (57,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','BBD','xe.com-paid xml feed',1.62247,1.62247,1,1.62247,1.62247,1.62247,1.62247,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (58,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','INR','xe.com-paid xml feed',39.0873,39.0873,1,39.0873,39.0873,39.0873,39.0873,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDINR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (59,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','GBP','xe.com-paid xml feed',0.562145,0.562145,1,0.562145,0.562145,0.562145,0.562145,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (60,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','EUR','xe.com-paid xml feed',0.623493,0.623493,1,0.623493,0.623493,0.623493,0.623493,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDEUR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (61,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','USD','xe.com-paid xml feed',0.5,0.5,1,0.5,0.5,0.5,0.5,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDBBD)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (62,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','AUD','xe.com-paid xml feed',0.770661,0.770661,1,0.770661,0.770661,0.770661,0.770661,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDBBD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (63,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','CAD','xe.com-paid xml feed',0.616345,0.616345,1,0.616345,0.616345,0.616345,0.616345,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDBBD))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (64,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','INR','xe.com-paid xml feed',24.0913,24.0913,1,24.0913,24.0913,24.0913,24.0913,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDINR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (65,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','GBP','xe.com-paid xml feed',0.346475,0.346475,1,0.346475,0.346475,0.346475,0.346475,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (66,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','EUR','xe.com-paid xml feed',0.384287,0.384287,1,0.384287,0.384287,0.384287,0.384287,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDEUR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (67,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','USD','xe.com-paid xml feed',0.0207544,0.0207544,1,0.0207544,0.0207544,0.0207544,0.0207544,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDINR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (68,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','AUD','xe.com-paid xml feed',0.0319892,0.0319892,1,0.0319892,0.0319892,0.0319892,0.0319892,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDINR))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (69,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','CAD','xe.com-paid xml feed',0.0255837,0.0255837,1,0.0255837,0.0255837,0.0255837,0.0255837,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDINR))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (70,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','BBD','xe.com-paid xml feed',0.0415088,0.0415088,1,0.0415088,0.0415088,0.0415088,0.0415088,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDINR))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (71,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','GBP','xe.com-paid xml feed',0.0143818,0.0143818,1,0.0143818,0.0143818,0.0143818,0.0143818,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDINR),USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (72,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','EUR','xe.com-paid xml feed',0.0159513,0.0159513,1,0.0159513,0.0159513,0.0159513,0.0159513,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDINR),USDEUR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (73,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','USD','xe.com-paid xml feed',1.44311,1.44311,1,1.44311,1.44311,1.44311,1.44311,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDGBP)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (74,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','AUD','xe.com-paid xml feed',2.22429,2.22429,1,2.22429,2.22429,2.22429,2.22429,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDGBP))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (75,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','CAD','xe.com-paid xml feed',1.7789,1.7789,1,1.7789,1.7789,1.7789,1.7789,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDGBP))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (76,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','BBD','xe.com-paid xml feed',2.88621,2.88621,1,2.88621,2.88621,2.88621,2.88621,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDGBP))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (77,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','INR','xe.com-paid xml feed',69.5325,69.5325,1,69.5325,69.5325,69.5325,69.5325,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDGBP))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (78,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','EUR','xe.com-paid xml feed',1.10913,1.10913,1,1.10913,1.10913,1.10913,1.10913,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDGBP),USDEUR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (79,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','USD','xe.com-paid xml feed',1.30111,1.30111,1,1.30111,1.30111,1.30111,1.30111,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDEUR)'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (80,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','AUD','xe.com-paid xml feed',2.00543,2.00543,1,2.00543,2.00543,2.00543,2.00543,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDEUR))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (81,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','CAD','xe.com-paid xml feed',1.60387,1.60387,1,1.60387,1.60387,1.60387,1.60387,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDEUR))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (82,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','BBD','xe.com-paid xml feed',2.60222,2.60222,1,2.60222,2.60222,2.60222,2.60222,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDEUR))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (83,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','INR','xe.com-paid xml feed',62.6909,62.6909,1,62.6909,62.6909,62.6909,62.6909,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDEUR))'); -INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (84,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','GBP','xe.com-paid xml feed',0.901606,0.901606,1,0.901606,0.901606,0.901606,0.901606,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDEUR))'); \ No newline at end of file +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (1,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','INR','',48.7792,48.7792,1,48.7792,48.7792,48.7792,48.7792,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (2,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','EUR','',0.798634,0.798634,1,0.798634,0.798634,0.798634,0.798634,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (3,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','AUD','',1.56747,1.56747,1,1.56747,1.56747,1.56747,1.56747,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (4,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','GBP','',0.682187,0.682187,1,0.682187,0.682187,0.682187,0.682187,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (5,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','CAD','',1.24183,1.24183,1,1.24183,1.24183,1.24183,1.24183,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (6,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','BBD','',1.995,1.995,1,1.995,1.995,1.995,1.995,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (7,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','USD','',0.0205006,0.0205006,1,0.0205006,0.0205006,0.0205006,0.0205006,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (8,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','EUR','',0.0163724,0.0163724,1,0.0163724,0.0163724,0.0163724,0.0163724,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (9,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','AUD','',0.032134,0.032134,1,0.032134,0.032134,0.032134,0.032134,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDAUD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (10,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','GBP','',0.0139852,0.0139852,1,0.0139852,0.0139852,0.0139852,0.0139852,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (11,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','CAD','',0.0254582,0.0254582,1,0.0254582,0.0254582,0.0254582,0.0254582,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (12,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','BBD','',0.0408986,0.0408986,1,0.0408986,0.0408986,0.0408986,0.0408986,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (13,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','USD','',1.25214,1.25214,1,1.25214,1.25214,1.25214,1.25214,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (14,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','INR','',61.0783,61.0783,1,61.0783,61.0783,61.0783,61.0783,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (15,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','AUD','',1.96269,1.96269,1,1.96269,1.96269,1.96269,1.96269,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDAUD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (16,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','GBP','',0.854193,0.854193,1,0.854193,0.854193,0.854193,0.854193,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (17,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','CAD','',1.55494,1.55494,1,1.55494,1.55494,1.55494,1.55494,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (18,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','BBD','',2.49802,2.49802,1,2.49802,2.49802,2.49802,2.49802,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (19,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','USD','',0.637971,0.637971,1,0.637971,0.637971,0.637971,0.637971,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDAUD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (20,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','INR','',31.1197,31.1197,1,31.1197,31.1197,31.1197,31.1197,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDAUD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (21,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','EUR','',0.509505,0.509505,1,0.509505,0.509505,0.509505,0.509505,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDAUD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (22,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','GBP','',0.435216,0.435216,1,0.435216,0.435216,0.435216,0.435216,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (23,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','CAD','',0.792251,0.792251,1,0.792251,0.792251,0.792251,0.792251,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (24,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','BBD','',1.27275,1.27275,1,1.27275,1.27275,1.27275,1.27275,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (25,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','USD','',1.46587,1.46587,1,1.46587,1.46587,1.46587,1.46587,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (26,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','INR','',71.5041,71.5041,1,71.5041,71.5041,71.5041,71.5041,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (27,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','EUR','',1.1707,1.1707,1,1.1707,1.1707,1.1707,1.1707,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (28,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','AUD','',2.29771,2.29771,1,2.29771,2.29771,2.29771,2.29771,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (29,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','CAD','',1.82036,1.82036,1,1.82036,1.82036,1.82036,1.82036,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDGBP),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (30,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','BBD','',2.92442,2.92442,1,2.92442,2.92442,2.92442,2.92442,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDGBP),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (31,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','USD','',0.805263,0.805263,1,0.805263,0.805263,0.805263,0.805263,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (32,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','INR','',39.2801,39.2801,1,39.2801,39.2801,39.2801,39.2801,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (33,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','EUR','',0.64311,0.64311,1,0.64311,0.64311,0.64311,0.64311,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (34,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','AUD','',1.26223,1.26223,1,1.26223,1.26223,1.26223,1.26223,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (35,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','GBP','',0.54934,0.54934,1,0.54934,0.54934,0.54934,0.54934,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (36,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','BBD','',1.6065,1.6065,1,1.6065,1.6065,1.6065,1.6065,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDCAD),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (37,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','USD','',0.501253,0.501253,1,0.501253,0.501253,0.501253,0.501253,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (38,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','INR','',24.4507,24.4507,1,24.4507,24.4507,24.4507,24.4507,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (39,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','EUR','',0.400318,0.400318,1,0.400318,0.400318,0.400318,0.400318,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (40,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','AUD','',0.785699,0.785699,1,0.785699,0.785699,0.785699,0.785699,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (41,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','GBP','',0.341949,0.341949,1,0.341949,0.341949,0.341949,0.341949,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (42,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','CAD','',0.622471,0.622471,1,0.622471,0.622471,0.622471,0.622471,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (43,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','AUD','',1.54132,1.54132,1,1.54132,1.54132,1.54132,1.54132,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (44,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','CAD','',1.23269,1.23269,1,1.23269,1.23269,1.23269,1.23269,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (45,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','BBD','',2,2,1,2,2,2,2,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (46,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','INR','',48.1826,48.1826,1,48.1826,48.1826,48.1826,48.1826,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (47,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','GBP','',0.69295,0.69295,1,0.69295,0.69295,0.69295,0.69295,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (48,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','EUR','',0.768573,0.768573,1,0.768573,0.768573,0.768573,0.768573,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (49,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','USD','',0.648794,0.648794,1,0.648794,0.648794,0.648794,0.648794,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDAUD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (50,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','CAD','',0.799762,0.799762,1,0.799762,0.799762,0.799762,0.799762,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (51,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','BBD','',1.29759,1.29759,1,1.29759,1.29759,1.29759,1.29759,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (52,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','INR','',31.2606,31.2606,1,31.2606,31.2606,31.2606,31.2606,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (53,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','GBP','',0.449582,0.449582,1,0.449582,0.449582,0.449582,0.449582,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (54,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','EUR','',0.498646,0.498646,1,0.498646,0.498646,0.498646,0.498646,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (55,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','USD','',0.811234,0.811234,1,0.811234,0.811234,0.811234,0.811234,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (56,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','AUD','',1.25037,1.25037,1,1.25037,1.25037,1.25037,1.25037,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (57,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','BBD','',1.62247,1.62247,1,1.62247,1.62247,1.62247,1.62247,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (58,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','INR','',39.0873,39.0873,1,39.0873,39.0873,39.0873,39.0873,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (59,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','GBP','',0.562145,0.562145,1,0.562145,0.562145,0.562145,0.562145,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (60,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','EUR','',0.623493,0.623493,1,0.623493,0.623493,0.623493,0.623493,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (61,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','USD','',0.5,0.5,1,0.5,0.5,0.5,0.5,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (62,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','AUD','',0.770661,0.770661,1,0.770661,0.770661,0.770661,0.770661,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (63,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','CAD','',0.616345,0.616345,1,0.616345,0.616345,0.616345,0.616345,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (64,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','INR','',24.0913,24.0913,1,24.0913,24.0913,24.0913,24.0913,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (65,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','GBP','',0.346475,0.346475,1,0.346475,0.346475,0.346475,0.346475,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (66,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','EUR','',0.384287,0.384287,1,0.384287,0.384287,0.384287,0.384287,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (67,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','USD','',0.0207544,0.0207544,1,0.0207544,0.0207544,0.0207544,0.0207544,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (68,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','AUD','',0.0319892,0.0319892,1,0.0319892,0.0319892,0.0319892,0.0319892,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDINR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (69,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','CAD','',0.0255837,0.0255837,1,0.0255837,0.0255837,0.0255837,0.0255837,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDINR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (70,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','BBD','',0.0415088,0.0415088,1,0.0415088,0.0415088,0.0415088,0.0415088,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDINR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (71,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','GBP','',0.0143818,0.0143818,1,0.0143818,0.0143818,0.0143818,0.0143818,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDINR),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (72,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','EUR','',0.0159513,0.0159513,1,0.0159513,0.0159513,0.0159513,0.0159513,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDINR),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (73,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','USD','',1.44311,1.44311,1,1.44311,1.44311,1.44311,1.44311,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (74,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','AUD','',2.22429,2.22429,1,2.22429,2.22429,2.22429,2.22429,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (75,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','CAD','',1.7789,1.7789,1,1.7789,1.7789,1.7789,1.7789,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (76,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','BBD','',2.88621,2.88621,1,2.88621,2.88621,2.88621,2.88621,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (77,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','INR','',69.5325,69.5325,1,69.5325,69.5325,69.5325,69.5325,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (78,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','EUR','',1.10913,1.10913,1,1.10913,1.10913,1.10913,1.10913,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDGBP),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (79,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','USD','',1.30111,1.30111,1,1.30111,1.30111,1.30111,1.30111,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (80,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','AUD','',2.00543,2.00543,1,2.00543,2.00543,2.00543,2.00543,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (81,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','CAD','',1.60387,1.60387,1,1.60387,1.60387,1.60387,1.60387,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (82,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','BBD','',2.60222,2.60222,1,2.60222,2.60222,2.60222,2.60222,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (83,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','INR','',62.6909,62.6909,1,62.6909,62.6909,62.6909,62.6909,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (84,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','GBP','',0.901606,0.901606,1,0.901606,0.901606,0.901606,0.901606,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDEUR))'); \ No newline at end of file
acvwilson/currency
e522e8b1c6affefda85103f88f9d836ca64a6d02
Added sample currency data and 174 currency codes (for specs)
diff --git a/spec/db/currency_codes.sql b/spec/db/currency_codes.sql new file mode 100644 index 0000000..85d1a43 --- /dev/null +++ b/spec/db/currency_codes.sql @@ -0,0 +1,171 @@ +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (1,'AED','United Arab Emirates Dirhams','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (2,'AFN','Afghanistan Afghanis','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (3,'ALL','Albania Leke','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (4,'AMD','Armenia Drams','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (5,'ANG','Netherlands Antilles Guilders','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (6,'AOA','Angola Kwanza','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (7,'ARS','Argentina Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (8,'AUD','Australia Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (9,'AWG','Aruba Guilders','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (10,'AZN','Azerbaijan New Manats','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (11,'BAM','Bosnia and Herzegovina Convertible Marka','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (12,'BBD','Barbados Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (13,'BDT','Bangladesh Taka','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (14,'BGN','Bulgaria Leva','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (15,'BHD','Bahrain Dinars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (16,'BIF','Burundi Francs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (17,'BMD','Bermuda Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (18,'BND','Brunei Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (19,'BOB','Bolivia Bolivianos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (20,'BRL','Brazil Reais','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (21,'BSD','Bahamas Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (22,'BTN','Bhutan Ngultrum','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (23,'BWP','Botswana Pulas','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (24,'BYR','Belarus Rubles','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (25,'BZD','Belize Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (26,'CAD','Canada Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (27,'CDF','Congo/Kinshasa Francs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (28,'CHF','Switzerland Francs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (29,'CLP','Chile Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (30,'CNY','China Yuan Renminbi','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (31,'COP','Colombia Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (32,'CRC','Costa Rica Colones','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (33,'CUC','Cuba Convertible Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (34,'CUP','Cuba Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (35,'CVE','Cape Verde Escudos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (36,'CZK','Czech Republic Koruny','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (37,'DJF','Djibouti Francs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (38,'DKK','Denmark Kroner','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (39,'DOP','Dominican Republic Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (40,'DZD','Algeria Dinars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (41,'EEK','Estonia Krooni','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (42,'EGP','Egypt Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (43,'ERN','Eritrea Nakfa','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (44,'ETB','Ethiopia Birr','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (45,'EUR','Euro','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (46,'FJD','Fiji Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (47,'FKP','Falkland Islands Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (48,'GBP','United Kingdom Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (49,'GEL','Georgia Lari','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (50,'GGP','Guernsey Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (51,'GHS','Ghana Cedis','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (52,'GIP','Gibraltar Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (53,'GMD','Gambia Dalasi','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (54,'GNF','Guinea Francs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (55,'GTQ','Guatemala Quetzales','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (56,'GYD','Guyana Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (57,'HKD','Hong Kong Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (58,'HNL','Honduras Lempiras','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (59,'HRK','Croatia Kuna','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (60,'HTG','Haiti Gourdes','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (61,'HUF','Hungary Forint','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (62,'IDR','Indonesia Rupiahs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (63,'ILS','Israel New Shekels','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (64,'IMP','Isle of Man Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (65,'INR','India Rupees','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (66,'IQD','Iraq Dinars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (67,'IRR','Iran Rials','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (68,'ISK','Iceland Kronur','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (69,'JEP','Jersey Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (70,'JMD','Jamaica Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (71,'JOD','Jordan Dinars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (72,'JPY','Japan Yen','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (73,'KES','Kenya Shillings','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (74,'KGS','Kyrgyzstan Soms','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (75,'KHR','Cambodia Riels','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (76,'KMF','Comoros Francs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (77,'KPW','North Korea Won','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (78,'KRW','South Korea Won','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (79,'KWD','Kuwait Dinars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (80,'KYD','Cayman Islands Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (81,'KZT','Kazakhstan Tenge','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (82,'LAK','Laos Kips','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (83,'LBP','Lebanon Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (84,'LKR','Sri Lanka Rupees','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (85,'LRD','Liberia Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (86,'LSL','Lesotho Maloti','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (87,'LTL','Lithuania Litai','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (88,'LVL','Latvia Lati','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (89,'LYD','Libya Dinars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (90,'MAD','Morocco Dirhams','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (91,'MDL','Moldova Lei','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (92,'MGA','Madagascar Ariary','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (93,'MKD','Macedonia Denars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (94,'MMK','Myanmar Kyats','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (95,'MNT','Mongolia Tugriks','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (96,'MOP','Macau Patacas','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (97,'MRO','Mauritania Ouguiyas','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (98,'MUR','Mauritius Rupees','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (99,'MVR','Maldives Rufiyaa','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (100,'MWK','Malawi Kwachas','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (101,'MXN','Mexico Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (102,'MYR','Malaysia Ringgits','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (103,'MZN','Mozambique Meticais','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (104,'NAD','Namibia Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (105,'NGN','Nigeria Nairas','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (106,'NIO','Nicaragua Cordobas','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (107,'NOK','Norway Kroner','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (108,'NPR','Nepal Rupees','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (109,'NZD','New Zealand Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (110,'OMR','Oman Rials','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (111,'PAB','Panama Balboas','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (112,'PEN','Peru Nuevos Soles','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (113,'PGK','Papua New Guinea Kina','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (114,'PHP','Philippines Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (115,'PKR','Pakistan Rupees','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (116,'PLN','Poland Zlotych','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (117,'PYG','Paraguay Guarani','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (118,'QAR','Qatar Riyals','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (119,'RON','Romania New Lei','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (120,'RSD','Serbia Dinars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (121,'RUB','Russia Rubles','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (122,'RWF','Rwanda Francs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (123,'SAR','Saudi Arabia Riyals','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (124,'SBD','Solomon Islands Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (125,'SCR','Seychelles Rupees','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (126,'SDG','Sudan Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (127,'SEK','Sweden Kronor','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (128,'SGD','Singapore Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (129,'SHP','Saint Helena Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (130,'SKK','Slovakia Koruny','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (131,'SLL','Sierra Leone Leones','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (132,'SOS','Somalia Shillings','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (133,'SPL','Seborga Luigini','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (134,'SRD','Suriname Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (135,'STD','Sao Tome and Principe Dobras','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (136,'SVC','El Salvador Colones','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (137,'SYP','Syria Pounds','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (138,'SZL','Swaziland Emalangeni','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (139,'THB','Thailand Baht','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (140,'TJS','Tajikistan Somoni','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (141,'TMM','Turkmenistan Manats','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (142,'TND','Tunisia Dinars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (143,'TOP','Tonga Paanga','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (144,'TRY','Turkey New Lira','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (145,'TTD','Trinidad and Tobago Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (146,'TVD','Tuvalu Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (147,'TWD','Taiwan New Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (148,'TZS','Tanzania Shillings','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (149,'UAH','Ukraine Hryvnia','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (150,'UGX','Uganda Shillings','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (151,'USD','United States Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (152,'UYU','Uruguay Pesos','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (153,'UZS','Uzbekistan Sums','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (154,'VEB','Venezuela Bolivares','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (155,'VEF','Venezuela Bolivares Fuertes','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (156,'VND','Vietnam Dong','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (157,'VUV','Vanuatu Vatu','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (158,'WST','Samoa Tala','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (159,'XAF','Communaute Financiere Africaine Francs BEAC','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (160,'XAG','Silver Ounces','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (161,'XAU','Gold Ounces','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (162,'XCD','East Caribbean Dollars','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (163,'XDR','International Monetary Fund Special Drawing Rights','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (164,'XOF','Communaute Financiere Africaine Francs BCEAO','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (165,'XPD','Palladium Ounces','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (166,'XPF','Comptoirs Francais du Pacifique Francs','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (167,'XPT','Platinum Ounces','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (168,'YER','Yemen Rials','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (169,'ZAR','South Africa Rand','2009-02-17 00:30:42','2009-02-17 00:30:42'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (170,'ZMK','Zambia Kwacha','2009-02-17 00:30:43','2009-02-17 00:30:43'); +INSERT INTO `currency_codes` (`id`,`code`,`name`,`created_at`,`updated_at`) VALUES (171,'ZWD','Zimbabwe Dollars','2009-02-17 00:30:43','2009-02-17 00:30:43'); diff --git a/spec/db/currency_historical_rates.sql b/spec/db/currency_historical_rates.sql new file mode 100644 index 0000000..46d71e8 --- /dev/null +++ b/spec/db/currency_historical_rates.sql @@ -0,0 +1,84 @@ +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (1,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','INR','xe.com-paid xml feed',48.7792,48.7792,1,48.7792,48.7792,48.7792,48.7792,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (2,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','EUR','xe.com-paid xml feed',0.798634,0.798634,1,0.798634,0.798634,0.798634,0.798634,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (3,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','AUD','xe.com-paid xml feed',1.56747,1.56747,1,1.56747,1.56747,1.56747,1.56747,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (4,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','GBP','xe.com-paid xml feed',0.682187,0.682187,1,0.682187,0.682187,0.682187,0.682187,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (5,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','CAD','xe.com-paid xml feed',1.24183,1.24183,1,1.24183,1.24183,1.24183,1.24183,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (6,'2008-11-17 20:00:19','2008-11-17 20:00:19','USD','BBD','xe.com-paid xml feed',1.995,1.995,1,1.995,1.995,1.995,1.995,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (7,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','USD','xe.com-paid xml feed',0.0205006,0.0205006,1,0.0205006,0.0205006,0.0205006,0.0205006,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (8,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','EUR','xe.com-paid xml feed',0.0163724,0.0163724,1,0.0163724,0.0163724,0.0163724,0.0163724,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (9,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','AUD','xe.com-paid xml feed',0.032134,0.032134,1,0.032134,0.032134,0.032134,0.032134,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDAUD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (10,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','GBP','xe.com-paid xml feed',0.0139852,0.0139852,1,0.0139852,0.0139852,0.0139852,0.0139852,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (11,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','CAD','xe.com-paid xml feed',0.0254582,0.0254582,1,0.0254582,0.0254582,0.0254582,0.0254582,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (12,'2008-11-17 20:00:19','2008-11-17 20:00:19','INR','BBD','xe.com-paid xml feed',0.0408986,0.0408986,1,0.0408986,0.0408986,0.0408986,0.0408986,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDINR),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (13,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','USD','xe.com-paid xml feed',1.25214,1.25214,1,1.25214,1.25214,1.25214,1.25214,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (14,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','INR','xe.com-paid xml feed',61.0783,61.0783,1,61.0783,61.0783,61.0783,61.0783,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (15,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','AUD','xe.com-paid xml feed',1.96269,1.96269,1,1.96269,1.96269,1.96269,1.96269,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDAUD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (16,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','GBP','xe.com-paid xml feed',0.854193,0.854193,1,0.854193,0.854193,0.854193,0.854193,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (17,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','CAD','xe.com-paid xml feed',1.55494,1.55494,1,1.55494,1.55494,1.55494,1.55494,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (18,'2008-11-17 20:00:20','2008-11-17 20:00:20','EUR','BBD','xe.com-paid xml feed',2.49802,2.49802,1,2.49802,2.49802,2.49802,2.49802,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDEUR),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (19,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','USD','xe.com-paid xml feed',0.637971,0.637971,1,0.637971,0.637971,0.637971,0.637971,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDAUD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (20,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','INR','xe.com-paid xml feed',31.1197,31.1197,1,31.1197,31.1197,31.1197,31.1197,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDAUD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (21,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','EUR','xe.com-paid xml feed',0.509505,0.509505,1,0.509505,0.509505,0.509505,0.509505,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDAUD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (22,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','GBP','xe.com-paid xml feed',0.435216,0.435216,1,0.435216,0.435216,0.435216,0.435216,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (23,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','CAD','xe.com-paid xml feed',0.792251,0.792251,1,0.792251,0.792251,0.792251,0.792251,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (24,'2008-11-17 20:00:20','2008-11-17 20:00:20','AUD','BBD','xe.com-paid xml feed',1.27275,1.27275,1,1.27275,1.27275,1.27275,1.27275,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDAUD),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (25,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','USD','xe.com-paid xml feed',1.46587,1.46587,1,1.46587,1.46587,1.46587,1.46587,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (26,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','INR','xe.com-paid xml feed',71.5041,71.5041,1,71.5041,71.5041,71.5041,71.5041,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (27,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','EUR','xe.com-paid xml feed',1.1707,1.1707,1,1.1707,1.1707,1.1707,1.1707,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (28,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','AUD','xe.com-paid xml feed',2.29771,2.29771,1,2.29771,2.29771,2.29771,2.29771,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (29,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','CAD','xe.com-paid xml feed',1.82036,1.82036,1,1.82036,1.82036,1.82036,1.82036,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDGBP),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (30,'2008-11-17 20:00:20','2008-11-17 20:00:20','GBP','BBD','xe.com-paid xml feed',2.92442,2.92442,1,2.92442,2.92442,2.92442,2.92442,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDGBP),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (31,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','USD','xe.com-paid xml feed',0.805263,0.805263,1,0.805263,0.805263,0.805263,0.805263,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (32,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','INR','xe.com-paid xml feed',39.2801,39.2801,1,39.2801,39.2801,39.2801,39.2801,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (33,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','EUR','xe.com-paid xml feed',0.64311,0.64311,1,0.64311,0.64311,0.64311,0.64311,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (34,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','AUD','xe.com-paid xml feed',1.26223,1.26223,1,1.26223,1.26223,1.26223,1.26223,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (35,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','GBP','xe.com-paid xml feed',0.54934,0.54934,1,0.54934,0.54934,0.54934,0.54934,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (36,'2008-11-17 20:00:20','2008-11-17 20:00:20','CAD','BBD','xe.com-paid xml feed',1.6065,1.6065,1,1.6065,1.6065,1.6065,1.6065,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','pivot(USD,reciprocal(USDCAD),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (37,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','USD','xe.com-paid xml feed',0.501253,0.501253,1,0.501253,0.501253,0.501253,0.501253,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (38,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','INR','xe.com-paid xml feed',24.4507,24.4507,1,24.4507,24.4507,24.4507,24.4507,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (39,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','EUR','xe.com-paid xml feed',0.400318,0.400318,1,0.400318,0.400318,0.400318,0.400318,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDEUR),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (40,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','AUD','xe.com-paid xml feed',0.785699,0.785699,1,0.785699,0.785699,0.785699,0.785699,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (41,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','GBP','xe.com-paid xml feed',0.341949,0.341949,1,0.341949,0.341949,0.341949,0.341949,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (42,'2008-11-17 20:00:20','2008-11-17 20:00:20','BBD','CAD','xe.com-paid xml feed',0.622471,0.622471,1,0.622471,0.622471,0.622471,0.622471,'2008-11-17 00:00:00','2008-11-17 00:00:00','2008-11-18 00:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (43,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','AUD','xe.com-paid xml feed',1.54132,1.54132,1,1.54132,1.54132,1.54132,1.54132,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (44,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','CAD','xe.com-paid xml feed',1.23269,1.23269,1,1.23269,1.23269,1.23269,1.23269,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (45,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','BBD','xe.com-paid xml feed',2,2,1,2,2,2,2,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (46,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','INR','xe.com-paid xml feed',48.1826,48.1826,1,48.1826,48.1826,48.1826,48.1826,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (47,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','GBP','xe.com-paid xml feed',0.69295,0.69295,1,0.69295,0.69295,0.69295,0.69295,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (48,'2009-02-04 14:53:07','2009-02-04 14:53:07','USD','EUR','xe.com-paid xml feed',0.768573,0.768573,1,0.768573,0.768573,0.768573,0.768573,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00',NULL); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (49,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','USD','xe.com-paid xml feed',0.648794,0.648794,1,0.648794,0.648794,0.648794,0.648794,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDAUD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (50,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','CAD','xe.com-paid xml feed',0.799762,0.799762,1,0.799762,0.799762,0.799762,0.799762,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (51,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','BBD','xe.com-paid xml feed',1.29759,1.29759,1,1.29759,1.29759,1.29759,1.29759,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (52,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','INR','xe.com-paid xml feed',31.2606,31.2606,1,31.2606,31.2606,31.2606,31.2606,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (53,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','GBP','xe.com-paid xml feed',0.449582,0.449582,1,0.449582,0.449582,0.449582,0.449582,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (54,'2009-02-04 14:53:07','2009-02-04 14:53:07','AUD','EUR','xe.com-paid xml feed',0.498646,0.498646,1,0.498646,0.498646,0.498646,0.498646,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDAUD),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (55,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','USD','xe.com-paid xml feed',0.811234,0.811234,1,0.811234,0.811234,0.811234,0.811234,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDCAD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (56,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','AUD','xe.com-paid xml feed',1.25037,1.25037,1,1.25037,1.25037,1.25037,1.25037,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDCAD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (57,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','BBD','xe.com-paid xml feed',1.62247,1.62247,1,1.62247,1.62247,1.62247,1.62247,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (58,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','INR','xe.com-paid xml feed',39.0873,39.0873,1,39.0873,39.0873,39.0873,39.0873,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (59,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','GBP','xe.com-paid xml feed',0.562145,0.562145,1,0.562145,0.562145,0.562145,0.562145,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (60,'2009-02-04 14:53:07','2009-02-04 14:53:07','CAD','EUR','xe.com-paid xml feed',0.623493,0.623493,1,0.623493,0.623493,0.623493,0.623493,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDCAD),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (61,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','USD','xe.com-paid xml feed',0.5,0.5,1,0.5,0.5,0.5,0.5,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDBBD)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (62,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','AUD','xe.com-paid xml feed',0.770661,0.770661,1,0.770661,0.770661,0.770661,0.770661,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (63,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','CAD','xe.com-paid xml feed',0.616345,0.616345,1,0.616345,0.616345,0.616345,0.616345,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDBBD))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (64,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','INR','xe.com-paid xml feed',24.0913,24.0913,1,24.0913,24.0913,24.0913,24.0913,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (65,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','GBP','xe.com-paid xml feed',0.346475,0.346475,1,0.346475,0.346475,0.346475,0.346475,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (66,'2009-02-04 14:53:07','2009-02-04 14:53:07','BBD','EUR','xe.com-paid xml feed',0.384287,0.384287,1,0.384287,0.384287,0.384287,0.384287,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDBBD),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (67,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','USD','xe.com-paid xml feed',0.0207544,0.0207544,1,0.0207544,0.0207544,0.0207544,0.0207544,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDINR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (68,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','AUD','xe.com-paid xml feed',0.0319892,0.0319892,1,0.0319892,0.0319892,0.0319892,0.0319892,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDINR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (69,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','CAD','xe.com-paid xml feed',0.0255837,0.0255837,1,0.0255837,0.0255837,0.0255837,0.0255837,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDINR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (70,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','BBD','xe.com-paid xml feed',0.0415088,0.0415088,1,0.0415088,0.0415088,0.0415088,0.0415088,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDINR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (71,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','GBP','xe.com-paid xml feed',0.0143818,0.0143818,1,0.0143818,0.0143818,0.0143818,0.0143818,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDINR),USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (72,'2009-02-04 14:53:07','2009-02-04 14:53:07','INR','EUR','xe.com-paid xml feed',0.0159513,0.0159513,1,0.0159513,0.0159513,0.0159513,0.0159513,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDINR),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (73,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','USD','xe.com-paid xml feed',1.44311,1.44311,1,1.44311,1.44311,1.44311,1.44311,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDGBP)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (74,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','AUD','xe.com-paid xml feed',2.22429,2.22429,1,2.22429,2.22429,2.22429,2.22429,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (75,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','CAD','xe.com-paid xml feed',1.7789,1.7789,1,1.7789,1.7789,1.7789,1.7789,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (76,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','BBD','xe.com-paid xml feed',2.88621,2.88621,1,2.88621,2.88621,2.88621,2.88621,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (77,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','INR','xe.com-paid xml feed',69.5325,69.5325,1,69.5325,69.5325,69.5325,69.5325,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDGBP))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (78,'2009-02-04 14:53:07','2009-02-04 14:53:07','GBP','EUR','xe.com-paid xml feed',1.10913,1.10913,1,1.10913,1.10913,1.10913,1.10913,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','pivot(USD,reciprocal(USDGBP),USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (79,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','USD','xe.com-paid xml feed',1.30111,1.30111,1,1.30111,1.30111,1.30111,1.30111,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(USDEUR)'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (80,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','AUD','xe.com-paid xml feed',2.00543,2.00543,1,2.00543,2.00543,2.00543,2.00543,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDAUD),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (81,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','CAD','xe.com-paid xml feed',1.60387,1.60387,1,1.60387,1.60387,1.60387,1.60387,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDCAD),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (82,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','BBD','xe.com-paid xml feed',2.60222,2.60222,1,2.60222,2.60222,2.60222,2.60222,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDBBD),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (83,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','INR','xe.com-paid xml feed',62.6909,62.6909,1,62.6909,62.6909,62.6909,62.6909,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDINR),USDEUR))'); +INSERT INTO `currency_historical_rates` (`id`,`created_on`,`updated_on`,`c1`,`c2`,`source`,`rate`,`rate_avg`,`rate_samples`,`rate_lo`,`rate_hi`,`rate_date_0`,`rate_date_1`,`date`,`date_0`,`date_1`,`derived`) VALUES (84,'2009-02-04 14:53:07','2009-02-04 14:53:07','EUR','GBP','xe.com-paid xml feed',0.901606,0.901606,1,0.901606,0.901606,0.901606,0.901606,'2009-02-04 00:00:00','2009-02-02 23:00:00','2009-02-03 23:00:00','reciprocal(pivot(USD,reciprocal(USDGBP),USDEUR))'); \ No newline at end of file diff --git a/spec/db/database.yml b/spec/db/database.yml new file mode 100644 index 0000000..a9ef4e3 --- /dev/null +++ b/spec/db/database.yml @@ -0,0 +1,10 @@ +sqlite3mem: + :adapter: sqlite3 + :dbfile: ":memory:" + +mysql_debug: + adapter: mysql + database: currency_gem_test + username: root + socket: /opt/local/var/run/mysql5/mysqld.sock + encoding: utf8 diff --git a/spec/db/schema.rb b/spec/db/schema.rb new file mode 100644 index 0000000..3a65426 --- /dev/null +++ b/spec/db/schema.rb @@ -0,0 +1,44 @@ +ActiveRecord::Schema.define(:version => 0) do + create_table :dogs, :force => true do |t| + t.column :name, :string + t.column :price, :integer, :limit => 8 + t.column :price_currency, :string, :limit => 5 + end + + create_table :currency_codes, :force => true do |t| + t.string :code, :limit => 5 + t.string :name + t.datetime :created_at + t.datetime :updated_at + end + + add_index :currency_codes, ["code"], :name => "index_currency_codes_on_code", :unique => true + + create_table :currency_historical_rates, :force => true do |t| + t.datetime :created_on, :null => false + t.datetime :updated_on + t.string :c1, :limit => 3, :null => false + t.string :c2, :limit => 3, :null => false + t.string :source, :limit => 32, :null => false + t.float :rate, :null => false + t.float :rate_avg + t.integer :rate_samples + t.float :rate_lo + t.float :rate_hi + t.float :rate_date_0 + t.float :rate_date_1 + t.datetime :date, :null => false + t.datetime :date_0 + t.datetime :date_1 + t.string :derived, :limit => 64 + end + + add_index :currency_historical_rates, ["c1", "c2", "source", "date_0", "date_1"], :name => :c1_c2_src_date_range, :unique => true + add_index :currency_historical_rates, ["c1"], :name => :index_currency_historical_rates_on_c1 + add_index :currency_historical_rates, ["c2"], :name => :index_currency_historical_rates_on_c2 + add_index :currency_historical_rates, ["date"], :name => :index_currency_historical_rates_on_date + add_index :currency_historical_rates, ["date_0"], :name => :index_currency_historical_rates_on_date_0 + add_index :currency_historical_rates, ["date_1"], :name => :index_currency_historical_rates_on_date_1 + add_index :currency_historical_rates, ["source"], :name => :index_currency_historical_rates_on_source + +end \ No newline at end of file
acvwilson/currency
3362ae57a0f431826ab299d1766ceb36683788f4
Added TODO to investigate multiple requires of 'money'
diff --git a/lib/currency.rb b/lib/currency.rb index 0c8f1f5..89090dc 100644 --- a/lib/currency.rb +++ b/lib/currency.rb @@ -1,143 +1,143 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # # = Currency # # The Currency package provides an object-oriented model of: # # * currencies # * exchanges # * exchange rates # * exchange rate sources # * monetary values # # The core classes are: # # * Currency::Money - uses a scaled integer representation of a monetary value and performs accurate conversions to and from string values. # * Currency::Currency - provides an object-oriented representation of a currency. # * Currency::Exchange::Base - the base class for a currency exchange rate provider. # * Currency::Exchange::Rate::Source::Base - the base class for an on-demand currency exchange rate data provider. # * Currency::Exchange::Rate::Source::Provider - the base class for a bulk exchange rate data provider. # * Currency::Exchange::Rate - represents a exchange rate between two currencies. # # # The example below uses Currency::Exchange::Xe to automatically get # exchange rates from http://xe.com/ : # # require 'currency' # require 'currency/exchange/rate/deriver' # require 'currency/exchange/rate/source/xe' # require 'currency/exchange/rate/source/timed_cache' # # # Rate source initialization # provider = Currency::Exchange::Rate::Source::Xe.new # deriver = Currency::Exchange::Rate::Deriver.new(:source => provider) # cache = Currency::Exchange::Rate::Source::TimedCache.new(:source => deriver) # Currency::Exchange::Rate::Source.default = cache # # usd = Currency::Money('6.78', :USD) # puts "usd = #{usd.format}" # cad = usd.convert(:CAD) # puts "cad = #{cad.format}" # # == ActiveRecord Suppport # # This package also contains ActiveRecord support for money values: # # require 'currency' # require 'currency/active_record' # # class Entry < ActiveRecord::Base # money :amount # end # # In the example above, the entries.amount database column is an INTEGER that represents US cents. # The currency code of the money value can be stored in an additional database column or a default currency can be used. # # == Recent Enhancements # # === Storage and retrival of historical exchange rates # # * See Currency::Exchange::Rate::Source::Historical # * See Currency::Exchange::Rate::Source::Historical::Writer # # === Automatic derivation of rates from base rates. # # * See Currency::Exchange::Rate::Deriver # # === Rate caching # # * See Currency::Exchange::Rate::Source::TimedCache # # === Rate Providers # # * See Currency::Exchange::Rate::Source::Xe # * See Currency::Exchange::Rate::Source::NewYorkFed # * See Currency::Exchange::Rate::Source::TheFinancials # # === Customizable formatting and parsing # # * See Currency::Formatter # * See Currency::Parser # # == Future Enhancements # # * Support for inflationary rates within a currency, e.g. $10 USD in the year 1955 converted to 2006 USD. # # == SVN Repo # # svn checkout svn://rubyforge.org/var/svn/currency/currency/trunk # # == Examples # # See the examples/ and test/ directorys # # == Author # # Kurt Stephens http://kurtstephens.com # # == Support # # http://rubyforge.org/forum/forum.php?forum_id=7643 # # == Copyright # # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # module Currency # Use this function instead of Money#new: # # Currency::Money("12.34", :CAD) # # Do not do this: # # Currency::Money.new("12.34", :CAD) # # See Money#new. def self.Money(*opts) return nil if opts.to_s.strip == '' Money.new(*opts) end end $:.unshift(File.expand_path(File.dirname(__FILE__))) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'currency/config' require 'currency/exception' require 'currency/money' require 'currency/currency' require 'currency/currency/factory' -require 'currency/money' +require 'currency/money' # TODO: Why require this twice? (dvd, 15-03-2009) require 'currency/parser' require 'currency/formatter' # require this one before the parser and enjoy the weird bugs! require 'currency/exchange' require 'currency/exchange/rate' require 'currency/exchange/rate/deriver' require 'currency/exchange/rate/source' require 'currency/exchange/rate/source/test' require 'currency/exchange/time_quantitizer' require 'currency/core_extensions' require 'active_support' # high(-er) precision rounding
acvwilson/currency
b8ef484379c5758d7cb6688d4f28fd82dfa4fd14
Changed: bumped version to 0.6.4 Fixed: #{attr_name}_before_type_cast was broken for non-default currency formatters (validates_numericality_of never passes). Kept original code in, with ample comment to ease any future debugging.
diff --git a/currency.gemspec b/currency.gemspec index f5197b3..3a01ceb 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| s.name = %q{currency} - s.version = "0.6.3" + s.version = "0.6.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.authors = ["Asa Wilson"] + s.authors = ["Asa Wilson", "David Palm"] s.date = %q{#{Date.today}} s.description = %q{Currency conversions for Ruby} - s.email = ["[email protected]"] + s.email = ["[email protected]", "[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} s.summary = %q{#{s.name} #{s.version}} end diff --git a/lib/currency/active_record.rb b/lib/currency/active_record.rb index 1ec5c05..5658767 100644 --- a/lib/currency/active_record.rb +++ b/lib/currency/active_record.rb @@ -1,264 +1,298 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'active_record/base' require File.join(File.dirname(__FILE__), '..', 'currency') # See Currency::ActiveRecord::ClassMethods class ActiveRecord::Base @@money_attributes = { } # Called by money macro when a money attribute # is created. def self.register_money_attribute(attr_opts) (@@money_attributes[attr_opts[:class]] ||= { })[attr_opts[:attr_name]] = attr_opts end # Returns an array of option hashes for all the money attributes of # this class. # # Superclass attributes are not included. def self.money_attributes_for_class(cls) (@@money_atttributes[cls] || { }).values end # Iterates through all known money attributes in all classes. # # each_money_attribute { | money_opts | # ... # } def self.each_money_attribute(&blk) @@money_attributes.each do | cls, hash | hash.each do | attr_name, attr_opts | yield attr_opts end end end end # class # See Currency::ActiveRecord::ClassMethods module Currency::ActiveRecord def self.append_features(base) # :nodoc: # $stderr.puts " Currency::ActiveRecord#append_features(#{base})" super base.extend(ClassMethods) end # == ActiveRecord Suppport # # Support for Money attributes in ActiveRecord::Base subclasses: # # require 'currency' # require 'currency/active_record' # # class Entry < ActiveRecord::Base # attr_money :amount # end # module ClassMethods # Deprecated: use attr_money. def money(*args) $stderr.puts "WARNING: money(#{args.inspect}) deprecated, use attr_money: in #{caller(1)[0]}" attr_money(*args) end # Defines a Money object attribute that is bound # to a database column. The database column to store the # Money value representation is assumed to be # INTEGER and will store Money#rep values. # # Options: # # :column => undef # # Defines the column to use for storing the money value. # Defaults to the attribute name. # # If this column is different from the attribute name, # the money object will intercept column=(x) to flush # any cached Money object. # # :currency => currency_code (e.g.: :USD) # # Defines the Currency to use for storing a normalized Money # value. # # All Money values will be converted to this Currency before # storing. This allows SQL summary operations, # like SUM(), MAX(), AVG(), etc., to produce meaningful results, # regardless of the initial currency specified. If this # option is used, subsequent reads will be in the specified # normalization :currency. # # :currency_column => undef # # Defines the name of the CHAR(3) column used to store and # retrieve the Money's Currency code. If this option is used, each # record may use a different Currency to store the result, such # that SQL summary operations, like SUM(), MAX(), AVG(), # may return meaningless results. # # :currency_preferred_column => undef # # Defines the name of a CHAR(3) column used to store and # retrieve the Money's Currency code. This option can be used # with normalized Money values to retrieve the Money value # in its original Currency, while # allowing SQL summary operations on the normalized Money values # to still be valid. # # :time => undef # # Defines the name of attribute used to # retrieve the Money's time. If this option is used, each # Money value will use this attribute during historical Currency # conversions. # # Money values can share a time value with other attributes # (e.g. a created_on column). # # If this option is true, the money time attribute will be named # "#{attr_name}_time" and :time_update will be true. # # :time_update => undef # # If true, the Money time value is updated upon setting the # money attribute. # def attr_money(attr_name, *opts) opts = Hash[*opts] attr_name = attr_name.to_s opts[:class] = self opts[:table] = self.table_name opts[:attr_name] = attr_name.to_sym ::ActiveRecord::Base.register_money_attribute(opts) column = opts[:column] || opts[:attr_name] opts[:column] = column if column.to_s != attr_name.to_s alias_accessor = <<-"end_eval" alias :before_money_#{column}=, :#{column}= def #{column}=(__value) @{attr_name} = nil # uncache before_money#{column} = __value end end_eval end currency = opts[:currency] currency_column = opts[:currency_column] if currency_column && ! currency_column.kind_of?(String) currency_column = currency_column.to_s currency_column = "#{column}_currency" end if currency_column read_currency = "read_attribute(:#{currency_column.to_s})" write_currency = "write_attribute(:#{currency_column}, #{attr_name}_money.nil? ? nil : #{attr_name}_money.currency.code.to_s)" end opts[:currency_column] = currency_column currency_preferred_column = opts[:currency_preferred_column] if currency_preferred_column currency_preferred_column = currency_preferred_column.to_s read_preferred_currency = "@#{attr_name} = @#{attr_name}.convert(read_attribute(:#{currency_preferred_column}))" write_preferred_currency = "write_attribute(:#{currency_preferred_column}, @#{attr_name}_money.currency.code)" end time = opts[:time] write_time = '' if time if time == true time = "#{attr_name}_time" opts[:time_update] = true end read_time = "self.#{time}" end opts[:time] = time if opts[:time_update] write_time = "self.#{time} = #{attr_name}_money && #{attr_name}_money.time" end currency ||= ':USD' time ||= 'nil' read_currency ||= currency read_time ||= time money_rep ||= "#{attr_name}_money.rep" validate_allow_nil = opts[:allow_nil] ? ', :allow_nil => true' : '' validate = "# Validation\n" validate << "\nvalidates_numericality_of :#{attr_name}#{validate_allow_nil}\n" validate << "\nvalidates_format_of :#{currency_column}, :with => /^[A-Z][A-Z][A-Z]$/#{validate_allow_nil}\n" if currency_column + # validate << "\nbefore_validation :debug_#{attr_name}_before_validate\n" + # + # validate << %Q{ + # def debug_#{attr_name}_before_validate + # logger.debug "\tValidating #{attr_name}. Allow nils? #{validate_allow_nil}" + # logger.debug "\t\t'#{attr_name}': '\#\{#{attr_name}.inspect\}' (class: '\#\{#{attr_name}.class\}')" + # logger.debug "\t\tcurrency column, '#{currency_column}': '\#\{#{currency_column}.inspect\}' (class: '\#\{#{currency_column}.class\}'), matches '/^[A-Z][A-Z][A-Z]$/': \#\{'#{currency_column}'.match(/^[A-Z][A-Z][A-Z]$/).to_a.inspect\}" + # end + # } alias_accessor ||= '' module_eval (opts[:module_eval] = x = <<-"end_eval"), __FILE__, __LINE__ #{validate} #{alias_accessor} def #{attr_name} # $stderr.puts " \#{self.class.name}##{attr_name}" unless @#{attr_name} #{attr_name}_rep = read_attribute(:#{column}) unless #{attr_name}_rep.nil? @#{attr_name} = ::Currency::Money.new_rep(#{attr_name}_rep, #{read_currency} || #{currency}, #{read_time} || #{time}) #{read_preferred_currency} end end @#{attr_name} end def #{attr_name}=(value) if value.nil? || value.to_s.strip == '' #{attr_name}_money = nil elsif value.kind_of?(Integer) || value.kind_of?(String) || value.kind_of?(Float) #{attr_name}_money = ::Currency::Money(value, #{currency}) #{write_preferred_currency} elsif value.kind_of?(::Currency::Money) #{attr_name}_money = value #{write_preferred_currency} #{write_currency ? write_currency : "#{attr_name}_money = #{attr_name}_money.convert(#{currency})"} else raise ::Currency::Exception::InvalidMoneyValue, value end @#{attr_name} = #{attr_name}_money # TODO: Really needed? Isn't the write_attribute enough? write_attribute(:#{column}, #{attr_name}_money.nil? ? nil : #{money_rep}) #{write_time} value end def #{attr_name}_before_type_cast - # FIXME: User cannot specify Currency - x = #{attr_name} - x &&= x.format(:symbol => false, :currency => false, :thousands => false) - x + #{attr_name}.to_f if #{attr_name} end end_eval +=begin + Replaced the _before_type_cast because it's buggy and weird: + + Bug: if the Currency::Formatter.default is set to include the currency code (:code => true) then the + call below to format() will leave the code in. When the validates_numericality_of kicks in it + can't cast to Float (yes, validates_numericality_of basically does just that) because of the "USD" + of the currency code and everything fails. All the time. + + Weird: assigning to "x" doesn't really make any sense, just useless overhead. Using the rare &&= is not a big + win over something like: + x && x.format(..., ...) + and actually longer too. + The intention of the _before_type_cast method is to return a raw, unformatted value. + When it does work, it returns a string on the form "123.456". Why not cast to Float right away? + Arguably, the "raw" currency value is the integer rep stored in the db, but that wouldn't work + very well with any known rails validations. I think casting to Float is reasonable. + The taste Kurt Stephens has for weird Ruby code never ceases to amaze me. + + :) + (dvd, 05-02-2009) + def #{attr_name}_before_type_cast + # FIXME: User cannot specify Currency + x = #{attr_name} + x &&= x.format(:symbol => false, :currency => false, :thousands => false) + x + end +=end + # $stderr.puts " CODE = #{x}" end end end ActiveRecord::Base.class_eval do include Currency::ActiveRecord end diff --git a/lib/currency/exchange/rate/source/historical/rate.rb b/lib/currency/exchange/rate/source/historical/rate.rb index 59d9746..c516071 100644 --- a/lib/currency/exchange/rate/source/historical/rate.rb +++ b/lib/currency/exchange/rate/source/historical/rate.rb @@ -1,184 +1,185 @@ require 'active_support' require 'active_record/base' require 'currency/exchange/rate/source/historical' # This class represents a historical Rate in a database. # It requires ActiveRecord. # class Currency::Exchange::Rate::Source::Historical::Rate < ::ActiveRecord::Base @@_table_name ||= Currency::Config.current.historical_table_name set_table_name @@_table_name # Can create a table and indices for this class # when passed a Migration. def self.__create_table(m, table_name = @@_table_name) table_name = table_name.intern m.instance_eval do create_table table_name do |t| t.column :created_on, :datetime, :null => false t.column :updated_on, :datetime t.column :c1, :string, :limit => 3, :null => false t.column :c2, :string, :limit => 3, :null => false t.column :source, :string, :limit => 32, :null => false t.column :rate, :float, :null => false t.column :rate_avg, :float t.column :rate_samples, :integer t.column :rate_lo, :float t.column :rate_hi, :float t.column :rate_date_0, :float t.column :rate_date_1, :float t.column :date, :datetime, :null => false t.column :date_0, :datetime t.column :date_1, :datetime t.column :derived, :string, :limit => 64 end add_index table_name, :c1 add_index table_name, :c2 add_index table_name, :source add_index table_name, :date add_index table_name, :date_0 add_index table_name, :date_1 add_index table_name, [:c1, :c2, :source, :date_0, :date_1], :name => 'c1_c2_src_date_range', :unique => true end end # Initializes this object from a Currency::Exchange::Rate object. def from_rate(rate) self.c1 = rate.c1.code.to_s self.c2 = rate.c2.code.to_s self.rate = rate.rate self.rate_avg = rate.rate_avg self.rate_samples = rate.rate_samples self.rate_lo = rate.rate_lo self.rate_hi = rate.rate_hi self.rate_date_0 = rate.rate_date_0 self.rate_date_1 = rate.rate_date_1 self.source = rate.source self.derived = rate.derived self.date = rate.date self.date_0 = rate.date_0 self.date_1 = rate.date_1 self end # Convert all dates to localtime. def dates_to_localtime! self.date = self.date && self.date.clone.localtime self.date_0 = self.date_0 && self.date_0.clone.localtime self.date_1 = self.date_1 && self.date_1.clone.localtime end # Creates a new Currency::Exchange::Rate object. def to_rate(cls = ::Currency::Exchange::Rate) cls. new( ::Currency::Currency.get(self.c1), ::Currency::Currency.get(self.c2), self.rate, "historical #{self.source}", self.date, self.derived, { :rate_avg => self.rate_avg, :rate_samples => self.rate_samples, :rate_lo => self.rate_lo, :rate_hi => self.rate_hi, :rate_date_0 => self.rate_date_0, :rate_date_1 => self.rate_date_1, :date_0 => self.date_0, :date_1 => self.date_1 }) end # Various defaults. def before_validation self.rate_avg = self.rate unless self.rate_avg self.rate_samples = 1 unless self.rate_samples self.rate_lo = self.rate unless self.rate_lo self.rate_hi = self.rate unless self.rate_hi self.rate_date_0 = self.rate unless self.rate_date_0 self.rate_date_1 = self.rate unless self.rate_date_1 #self.date_0 = self.date unless self.date_0 #self.date_1 = self.date unless self.date_1 self.date = self.date_0 + (self.date_1 - self.date_0) * 0.5 if ! self.date && self.date_0 && self.date_1 self.date = self.date_0 unless self.date self.date = self.date_1 unless self.date end # Returns a ActiveRecord::Base#find :conditions value # to locate any rates that will match this one. # # source may be a list of sources. # date will match inside date_0 ... date_1 or exactly. # def find_matching_this_conditions sql = [ ] values = [ ] if self.c1 sql << 'c1 = ?' values.push(self.c1.to_s) end if self.c2 sql << 'c2 = ?' values.push(self.c2.to_s) end if self.source if self.source.kind_of?(Array) sql << 'source IN ?' else sql << 'source = ?' end values.push(self.source) end if self.date sql << '(((date_0 IS NULL) OR (date_0 <= ?)) AND ((date_1 IS NULL) OR (date_1 > ?))) OR date = ?' values.push(self.date, self.date, self.date) end if self.date_0 sql << 'date_0 = ?' values.push(self.date_0) end if self.date_1 sql << 'date_1 = ?' values.push(self.date_1) end sql << '1 = 1' if sql.empty? values.unshift(sql.collect{|x| "(#{x})"}.join(' AND ')) # $stderr.puts "values = #{values.inspect}" values end # Shorthand. def find_matching_this(opt1 = :all, *opts) + # FIXME: this breaks somehow in Ruby 1.9 Not sure why. (dvd, 04-02-2009) self.class.find(opt1, :conditions => find_matching_this_conditions, *opts) end end # class
acvwilson/currency
ce3667b223f80091b3bcd94651ad99a7c6e333a2
Fixed: breakage when raising exception (a rare and exotic condition, but nonetheless...)
diff --git a/currency.gemspec b/currency.gemspec index ca7b12a..f5197b3 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| s.name = %q{currency} - s.version = "0.6.2" + s.version = "0.6.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] s.date = %q{#{Date.today}} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} s.summary = %q{#{s.name} #{s.version}} end diff --git a/lib/currency/exception.rb b/lib/currency/exception.rb index 734bc1f..91d1264 100644 --- a/lib/currency/exception.rb +++ b/lib/currency/exception.rb @@ -1,119 +1,119 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. module Currency::Exception # Base class for all Currency::Exception objects. # # raise Currency::Exception [ "msg", :opt1, 1, :opt2, 2 ] # class Base < ::StandardError EMPTY_HASH = { }.freeze def initialize(arg1, *args) case arg1 # [ description, ... ] when Array @opts = arg1 arg1 = arg1.shift else @opts = nil end case @opts when Array if @opts.size == 1 && @opts.first.kind_of?(Hash) # [ description, { ... } ] @opts = @opts.first else # [ description, :key, value, ... ] @opts = Hash[*@opts] end end case @opts when Hash @opts = @opts.dup.freeze else @opts = { :info => @opts }.freeze end @opts ||= EMPTY_HASH super(arg1, *args) end def method_missing(sel, *args, &blk) sel = sel.to_sym if args.empty? && ! block_given? && @opts.key?(sel) return @opts[sel] end super end def to_s - super + ": #{@opts.inspect}" + "#{super}: #{@opts.inspect}" end end # Generic Error. class Generic < Base end # Error during parsing of Money values from String. class InvalidMoneyString < Base end # Error during coercion of external Money values. class InvalidMoneyValue < Base end # Error in Currency code formeat. class InvalidCurrencyCode < Base end # Error during conversion between currencies. class IncompatibleCurrency < Base end # Error during locating currencies. class MissingCurrency < Base end # Error if an Exchange is not defined. class UndefinedExchange < Base end # Error if a Currency is unknown. class UnknownCurrency < Base end # Error if an Exchange Rate Source cannot provide an Exchange::Rate. class UnknownRate < Base end # Error if an Exchange Rate Source. class RateSourceError < Base end # Error if an Exchange Rate Source cannot supply any rates. class UnavailableRates < Base end # Error if an Exchange::Rate is not valid. class InvalidRate < Base end # Error if a subclass is responsible for implementing a method. class SubclassResponsibility < Base end # Error if some functionality is unimplemented class Unimplemented < Base end # Error if reentrantancy is d class InvalidReentrancy < Base end end # module
acvwilson/currency
5a8ebd09ac0612e1f6e40e93e513f2be3990b729
FIXED: broken indentation
diff --git a/lib/currency/money_helper.rb b/lib/currency/money_helper.rb index 015b4c0..2550a92 100644 --- a/lib/currency/money_helper.rb +++ b/lib/currency/money_helper.rb @@ -1,13 +1,13 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. module ActionView::Helpers::MoneyHelper - # Creates a suitable HTML element for a Money value field. - def money_field(object, method, options = {}) - InstanceTag.new(object, method, self).to_input_field_tag("text", options) - end + # Creates a suitable HTML element for a Money value field. + def money_field(object, method, options = {}) + InstanceTag.new(object, method, self).to_input_field_tag("text", options) + end end ActionView::Base.load_helper(File.dirname(__FILE__))
acvwilson/currency
70208950d9b12ef2b00049e7957d6fa03a2e582b
REMOVED: CurrencyVersion CHANGED: version bumped to 0.6.2 CHANGED: Currency::Money() factory method can now return nil when fed an empty string (breaking API CHANGE!!!) CHANGED: preferring .to_sym to .intern CHANGED: ActiveRecord attr_money setters doesn't try to write empty strings to the attribute, thusly avoiding exceptions when no Money object can be created CHANGED: Currency::Parser#_parse will return nil (and early) if fed an empty string CHANGED: Currency::Money.new will try its absolute best to create a Money object with decent defults even when passed unparseable data. Such Money objects are dangerous, as m.zero? wil return true, but better than straight exceptions. The safe way of instantiating Moneies is to use the Currency::Money() factory CHANGED: Refactored and improved the parser specs (yay!)
diff --git a/Manifest.txt b/Manifest.txt index f631c9b..abc748d 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,58 +1,57 @@ COPYING.txt ChangeLog LICENSE.txt Manifest.txt README.txt Rakefile Releases.txt TODO.txt bin/currency_historical_rate_load examples/ex1.rb examples/xe1.rb lib/currency.rb lib/currency/active_record.rb lib/currency/config.rb lib/currency/core_extensions.rb lib/currency/currency.rb lib/currency/currency/factory.rb -lib/currency/currency_version.rb lib/currency/exception.rb lib/currency/exchange.rb lib/currency/exchange/rate.rb lib/currency/exchange/rate/deriver.rb lib/currency/exchange/rate/source.rb lib/currency/exchange/rate/source/base.rb lib/currency/exchange/rate/source/failover.rb lib/currency/exchange/rate/source/federal_reserve.rb lib/currency/exchange/rate/source/historical.rb lib/currency/exchange/rate/source/historical/rate.rb lib/currency/exchange/rate/source/historical/rate_loader.rb lib/currency/exchange/rate/source/historical/writer.rb lib/currency/exchange/rate/source/new_york_fed.rb lib/currency/exchange/rate/source/provider.rb lib/currency/exchange/rate/source/test.rb lib/currency/exchange/rate/source/the_financials.rb lib/currency/exchange/rate/source/timed_cache.rb lib/currency/exchange/rate/source/xe.rb lib/currency/exchange/time_quantitizer.rb lib/currency/formatter.rb lib/currency/macro.rb lib/currency/money.rb lib/currency/money_helper.rb lib/currency/parser.rb test/ar_column_test.rb test/ar_simple_test.rb test/ar_test_base.rb test/ar_test_core.rb test/config_test.rb test/federal_reserve_test.rb test/formatter_test.rb test/historical_writer_test.rb test/macro_test.rb test/money_test.rb test/new_york_fed_test.rb test/parser_test.rb test/test_base.rb test/time_quantitizer_test.rb test/timed_cache_test.rb test/xe_test.rb diff --git a/currency.gemspec b/currency.gemspec index 02f1d38..15ec422 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| s.name = %q{currency} - s.version = "0.6.0" + s.version = "0.6.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] s.date = %q{#{Date.today}} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] - s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/currency_version.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] + s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} s.summary = %q{#{s.name} #{s.version}} end \ No newline at end of file diff --git a/lib/currency.rb b/lib/currency.rb index 8d98101..0c8f1f5 100644 --- a/lib/currency.rb +++ b/lib/currency.rb @@ -1,143 +1,143 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # # = Currency # # The Currency package provides an object-oriented model of: # # * currencies # * exchanges # * exchange rates # * exchange rate sources # * monetary values # # The core classes are: # # * Currency::Money - uses a scaled integer representation of a monetary value and performs accurate conversions to and from string values. # * Currency::Currency - provides an object-oriented representation of a currency. # * Currency::Exchange::Base - the base class for a currency exchange rate provider. # * Currency::Exchange::Rate::Source::Base - the base class for an on-demand currency exchange rate data provider. # * Currency::Exchange::Rate::Source::Provider - the base class for a bulk exchange rate data provider. # * Currency::Exchange::Rate - represents a exchange rate between two currencies. # # # The example below uses Currency::Exchange::Xe to automatically get # exchange rates from http://xe.com/ : # # require 'currency' # require 'currency/exchange/rate/deriver' # require 'currency/exchange/rate/source/xe' # require 'currency/exchange/rate/source/timed_cache' # # # Rate source initialization # provider = Currency::Exchange::Rate::Source::Xe.new # deriver = Currency::Exchange::Rate::Deriver.new(:source => provider) # cache = Currency::Exchange::Rate::Source::TimedCache.new(:source => deriver) # Currency::Exchange::Rate::Source.default = cache # # usd = Currency::Money('6.78', :USD) # puts "usd = #{usd.format}" # cad = usd.convert(:CAD) # puts "cad = #{cad.format}" # # == ActiveRecord Suppport # # This package also contains ActiveRecord support for money values: # # require 'currency' # require 'currency/active_record' # # class Entry < ActiveRecord::Base # money :amount # end # # In the example above, the entries.amount database column is an INTEGER that represents US cents. # The currency code of the money value can be stored in an additional database column or a default currency can be used. # # == Recent Enhancements # # === Storage and retrival of historical exchange rates # # * See Currency::Exchange::Rate::Source::Historical # * See Currency::Exchange::Rate::Source::Historical::Writer # # === Automatic derivation of rates from base rates. # # * See Currency::Exchange::Rate::Deriver # # === Rate caching # # * See Currency::Exchange::Rate::Source::TimedCache # # === Rate Providers # # * See Currency::Exchange::Rate::Source::Xe # * See Currency::Exchange::Rate::Source::NewYorkFed # * See Currency::Exchange::Rate::Source::TheFinancials # # === Customizable formatting and parsing # # * See Currency::Formatter # * See Currency::Parser # # == Future Enhancements # # * Support for inflationary rates within a currency, e.g. $10 USD in the year 1955 converted to 2006 USD. # # == SVN Repo # # svn checkout svn://rubyforge.org/var/svn/currency/currency/trunk # # == Examples # # See the examples/ and test/ directorys # # == Author # # Kurt Stephens http://kurtstephens.com # # == Support # # http://rubyforge.org/forum/forum.php?forum_id=7643 # # == Copyright # # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # module Currency # Use this function instead of Money#new: # # Currency::Money("12.34", :CAD) # # Do not do this: # # Currency::Money.new("12.34", :CAD) # # See Money#new. def self.Money(*opts) + return nil if opts.to_s.strip == '' Money.new(*opts) end end $:.unshift(File.expand_path(File.dirname(__FILE__))) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) -require 'currency/currency_version' require 'currency/config' require 'currency/exception' require 'currency/money' require 'currency/currency' require 'currency/currency/factory' require 'currency/money' require 'currency/parser' require 'currency/formatter' # require this one before the parser and enjoy the weird bugs! require 'currency/exchange' require 'currency/exchange/rate' require 'currency/exchange/rate/deriver' require 'currency/exchange/rate/source' require 'currency/exchange/rate/source/test' require 'currency/exchange/time_quantitizer' require 'currency/core_extensions' require 'active_support' # high(-er) precision rounding diff --git a/lib/currency/active_record.rb b/lib/currency/active_record.rb index a644ff1..1ec5c05 100644 --- a/lib/currency/active_record.rb +++ b/lib/currency/active_record.rb @@ -1,265 +1,264 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'active_record/base' require File.join(File.dirname(__FILE__), '..', 'currency') # See Currency::ActiveRecord::ClassMethods class ActiveRecord::Base @@money_attributes = { } # Called by money macro when a money attribute # is created. def self.register_money_attribute(attr_opts) (@@money_attributes[attr_opts[:class]] ||= { })[attr_opts[:attr_name]] = attr_opts end # Returns an array of option hashes for all the money attributes of # this class. # # Superclass attributes are not included. def self.money_attributes_for_class(cls) (@@money_atttributes[cls] || { }).values end # Iterates through all known money attributes in all classes. # # each_money_attribute { | money_opts | # ... # } def self.each_money_attribute(&blk) @@money_attributes.each do | cls, hash | hash.each do | attr_name, attr_opts | yield attr_opts end end end end # class # See Currency::ActiveRecord::ClassMethods module Currency::ActiveRecord def self.append_features(base) # :nodoc: # $stderr.puts " Currency::ActiveRecord#append_features(#{base})" super base.extend(ClassMethods) end # == ActiveRecord Suppport # # Support for Money attributes in ActiveRecord::Base subclasses: # # require 'currency' # require 'currency/active_record' # # class Entry < ActiveRecord::Base # attr_money :amount # end # module ClassMethods # Deprecated: use attr_money. def money(*args) $stderr.puts "WARNING: money(#{args.inspect}) deprecated, use attr_money: in #{caller(1)[0]}" attr_money(*args) end # Defines a Money object attribute that is bound # to a database column. The database column to store the # Money value representation is assumed to be # INTEGER and will store Money#rep values. # # Options: # # :column => undef # # Defines the column to use for storing the money value. # Defaults to the attribute name. # # If this column is different from the attribute name, # the money object will intercept column=(x) to flush # any cached Money object. # # :currency => currency_code (e.g.: :USD) # # Defines the Currency to use for storing a normalized Money # value. # # All Money values will be converted to this Currency before # storing. This allows SQL summary operations, # like SUM(), MAX(), AVG(), etc., to produce meaningful results, # regardless of the initial currency specified. If this # option is used, subsequent reads will be in the specified # normalization :currency. # # :currency_column => undef # # Defines the name of the CHAR(3) column used to store and # retrieve the Money's Currency code. If this option is used, each # record may use a different Currency to store the result, such # that SQL summary operations, like SUM(), MAX(), AVG(), # may return meaningless results. # # :currency_preferred_column => undef # # Defines the name of a CHAR(3) column used to store and # retrieve the Money's Currency code. This option can be used # with normalized Money values to retrieve the Money value # in its original Currency, while # allowing SQL summary operations on the normalized Money values # to still be valid. # # :time => undef # # Defines the name of attribute used to # retrieve the Money's time. If this option is used, each # Money value will use this attribute during historical Currency # conversions. # # Money values can share a time value with other attributes # (e.g. a created_on column). # # If this option is true, the money time attribute will be named # "#{attr_name}_time" and :time_update will be true. # # :time_update => undef # # If true, the Money time value is updated upon setting the # money attribute. # def attr_money(attr_name, *opts) opts = Hash[*opts] attr_name = attr_name.to_s opts[:class] = self opts[:table] = self.table_name - opts[:attr_name] = attr_name.intern + opts[:attr_name] = attr_name.to_sym ::ActiveRecord::Base.register_money_attribute(opts) column = opts[:column] || opts[:attr_name] opts[:column] = column if column.to_s != attr_name.to_s alias_accessor = <<-"end_eval" alias :before_money_#{column}=, :#{column}= def #{column}=(__value) @{attr_name} = nil # uncache before_money#{column} = __value end end_eval end currency = opts[:currency] currency_column = opts[:currency_column] if currency_column && ! currency_column.kind_of?(String) currency_column = currency_column.to_s currency_column = "#{column}_currency" end if currency_column read_currency = "read_attribute(:#{currency_column.to_s})" write_currency = "write_attribute(:#{currency_column}, #{attr_name}_money.nil? ? nil : #{attr_name}_money.currency.code.to_s)" end opts[:currency_column] = currency_column currency_preferred_column = opts[:currency_preferred_column] if currency_preferred_column currency_preferred_column = currency_preferred_column.to_s read_preferred_currency = "@#{attr_name} = @#{attr_name}.convert(read_attribute(:#{currency_preferred_column}))" write_preferred_currency = "write_attribute(:#{currency_preferred_column}, @#{attr_name}_money.currency.code)" end time = opts[:time] write_time = '' if time if time == true time = "#{attr_name}_time" opts[:time_update] = true end read_time = "self.#{time}" end opts[:time] = time if opts[:time_update] write_time = "self.#{time} = #{attr_name}_money && #{attr_name}_money.time" end currency ||= ':USD' time ||= 'nil' read_currency ||= currency read_time ||= time money_rep ||= "#{attr_name}_money.rep" validate_allow_nil = opts[:allow_nil] ? ', :allow_nil => true' : '' validate = "# Validation\n" validate << "\nvalidates_numericality_of :#{attr_name}#{validate_allow_nil}\n" validate << "\nvalidates_format_of :#{currency_column}, :with => /^[A-Z][A-Z][A-Z]$/#{validate_allow_nil}\n" if currency_column - alias_accessor ||= '' module_eval (opts[:module_eval] = x = <<-"end_eval"), __FILE__, __LINE__ #{validate} #{alias_accessor} def #{attr_name} # $stderr.puts " \#{self.class.name}##{attr_name}" unless @#{attr_name} #{attr_name}_rep = read_attribute(:#{column}) unless #{attr_name}_rep.nil? @#{attr_name} = ::Currency::Money.new_rep(#{attr_name}_rep, #{read_currency} || #{currency}, #{read_time} || #{time}) #{read_preferred_currency} end end @#{attr_name} end def #{attr_name}=(value) - if value.nil? + if value.nil? || value.to_s.strip == '' #{attr_name}_money = nil elsif value.kind_of?(Integer) || value.kind_of?(String) || value.kind_of?(Float) #{attr_name}_money = ::Currency::Money(value, #{currency}) #{write_preferred_currency} elsif value.kind_of?(::Currency::Money) #{attr_name}_money = value #{write_preferred_currency} #{write_currency ? write_currency : "#{attr_name}_money = #{attr_name}_money.convert(#{currency})"} else raise ::Currency::Exception::InvalidMoneyValue, value end - @#{attr_name} = #{attr_name}_money + @#{attr_name} = #{attr_name}_money # TODO: Really needed? Isn't the write_attribute enough? write_attribute(:#{column}, #{attr_name}_money.nil? ? nil : #{money_rep}) #{write_time} value end def #{attr_name}_before_type_cast # FIXME: User cannot specify Currency x = #{attr_name} x &&= x.format(:symbol => false, :currency => false, :thousands => false) x end end_eval # $stderr.puts " CODE = #{x}" end end end ActiveRecord::Base.class_eval do include Currency::ActiveRecord end diff --git a/lib/currency/currency_version.rb b/lib/currency/currency_version.rb deleted file mode 100644 index 1d3c9d0..0000000 --- a/lib/currency/currency_version.rb +++ /dev/null @@ -1,6 +0,0 @@ -module Currency - CurrencyVersion = '0.4.11' -end -# DO NOT EDIT -# This file is auto-generated by build scripts. -# See: rake update_version diff --git a/lib/currency/money.rb b/lib/currency/money.rb index 32b56f4..88372d6 100644 --- a/lib/currency/money.rb +++ b/lib/currency/money.rb @@ -1,293 +1,293 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # # Represents an amount of money in a particular currency. # # A Money object stores its value using a scaled Integer representation # and a Currency object. # # A Money object also has a time, which is used in conversions # against historical exchange rates. # class Currency::Money include Comparable @@default_time = nil def self.default_time @@default_time end def self.default_time=(x) @@default_time = x end @@empty_hash = { } @@empty_hash.freeze # # DO NOT CALL THIS DIRECTLY: # # See Currency.Money() function. # # Construct a Money value object # from a pre-scaled external representation: # where x is a Float, Integer, String, etc. # # If a currency is not specified, Currency.default is used. # # x.Money_rep(currency) # # is invoked to coerce x into a Money representation value. # # For example: # # 123.Money_rep(:USD) => 12300 # # Because the USD Currency object has a #scale of 100 # # See #Money_rep(currency) mixin. # def initialize(x, currency = nil, time = nil) @currency = ::Currency::Currency.get(currency) @time = time || ::Currency::Money.default_time @time = ::Currency::Money.now if @time == :now if x.kind_of?(String) if @currency m = @currency.parser_or_default.parse(x, :currency => @currency) else m = ::Currency::Parser.default.parse(x) end - @currency = m.currency unless @currency - @time = m.time if m.time - @rep = m.rep + @currency = m.currency if m && !@currency + @time = m.time if m && m.time + @rep = m.nil?? 0 : m.rep else @currency = ::Currency::Currency.default unless @currency @rep = x.Money_rep(@currency) end end # Returns a Time.new # Can be modifed for special purposes. def self.now Time.new end # Compatibility with Money package. def self.us_dollar(x) self.new(x, :USD) end # Compatibility with Money package. def cents @rep end # Construct from post-scaled internal representation. def self.new_rep(r, currency = nil, time = nil) x = self.new(0, currency, time) x.set_rep(r) x end # Construct from post-scaled internal representation. # using the same currency. # # x = Currency.Money("1.98", :USD) # x.new_rep(123) => USD $1.23 # # time defaults to self.time. def new_rep(r, time = nil) time ||= @time x = self.class.new(0, @currency, time) x.set_rep(r) x end # Do not call this method directly. # CLIENTS SHOULD NEVER CALL set_rep DIRECTLY. # You have been warned in ALL CAPS. def set_rep(r) # :nodoc: r = r.to_i unless r.kind_of?(Integer) @rep = r end # Do not call this method directly. # CLIENTS SHOULD NEVER CALL set_time DIRECTLY. # You have been warned in ALL CAPS. def set_time(time) # :nodoc: @time = time end # Returns the Money representation (usually an Integer). def rep @rep end # Get the Money's Currency. def currency @currency end # Get the Money's time. def time @time end # Convert Money to another Currency. # currency can be a Symbol or a Currency object. # If currency is nil, the Currency.default is used. def convert(currency, time = nil) currency = ::Currency::Currency.default if currency.nil? currency = ::Currency::Currency.get(currency) unless currency.kind_of?(Currency) if @currency == currency self else time = self.time if time == :money ::Currency::Exchange::Rate::Source.current.convert(self, currency, time) end end # Hash for hash table: both value and currency. # See #eql? below. def hash @rep.hash ^ @currency.hash end # True if money values have the same value and currency. def eql?(x) self.class == x.class && @rep == x.rep && @currency == x.currency end # True if money values have the same value and currency. def ==(x) self.class == x.class && @rep == x.rep && @currency == x.currency end # Compares Money values. # Will convert x to self.currency before comparision. def <=>(x) if @currency == x.currency @rep <=> x.rep else @rep <=> convert(@currency, @time).rep end end # - Money => Money # # Negates a Money value. def -@ new_rep(- @rep) end # Money + (Money | Number) => Money # # Right side may be coerced to left side's Currency. def +(x) new_rep(@rep + x.Money_rep(@currency)) end # Money - (Money | Number) => Money # # Right side may be coerced to left side's Currency. def -(x) new_rep(@rep - x.Money_rep(@currency)) end # Money * Number => Money # # Right side must be Number. def *(x) new_rep(@rep * x) end # Money / Money => Float (ratio) # Money / Number => Money # # Right side must be Money or Number. # Right side Integers are not coerced to Float before # division. def /(x) if x.kind_of?(self.class) (@rep.to_f) / (x.Money_rep(@currency).to_f) else new_rep(@rep / x) end end # Formats the Money value as a String using the Currency's Formatter. def format(*opt) @currency.format(self, *opt) end # Formats the Money value as a String. def to_s(*opt) @currency.format(self, *opt) end # Coerces the Money's value to a Float. # May cause loss of precision. def to_f Float(@rep) / @currency.scale end # Coerces the Money's value to an Integer. # May cause loss of precision. def to_i @rep / @currency.scale end # True if the Money's value is zero. def zero? @rep == 0 end # True if the Money's value is greater than zero. def positive? @rep > 0 end # True if the Money's value is less than zero. def negative? @rep < 0 end # Returns the Money's value representation in another currency. def Money_rep(currency, time = nil) # Attempt conversion? if @currency != currency || (time && @time != time) self.convert(currency, time).rep # raise ::Currency::Exception::Generic, "Incompatible Currency: #{@currency} != #{currency}" else @rep end end # Basic inspection, with symbol, currency code and time. # The standard #inspect method is available as #inspect_deep. def inspect(*opts) self.format(:symbol => true, :code => true, :time => true) end # How to alias a method defined in an object superclass in a different class: define_method(:inspect_deep, Object.instance_method(:inspect)) # How call a method defined in a superclass from a method with a different name: # def inspect_deep(*opts) # self.class.superclass.instance_method(:inspect).bind(self).call # end end # class diff --git a/lib/currency/parser.rb b/lib/currency/parser.rb index 2f70990..2033e8e 100644 --- a/lib/currency/parser.rb +++ b/lib/currency/parser.rb @@ -1,193 +1,196 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'rss/rss' # Time#xmlschema # This class parses a Money value from a String. # Each Currency has a default Parser. class Currency::Parser # The default Currency to use if no Currency is specified. attr_accessor :currency # If true and a parsed string contains a ISO currency code # that is not the same as currency, # #parse() will raise IncompatibleCurrency. # Defaults to false. attr_accessor :enforce_currency # The default Time to use if no Time is specified in the string. # If :now, time is set to Time.new. attr_accessor :time @@default = nil # Get the default Formatter. def self.default @@default ||= self.new end # Set the default Formatter. def self.default=(x) @@default = x end def initialize(opt = { }) @time = @enforce_currency = @currency = nil opt.each_pair{ | k, v | self.send("#{k}=", v) } end def _parse(str) # :nodoc: + return nil if str.to_s.strip == '' + x = str # Get currency. # puts "str = #{str.inspect}, @currency = #{@currency}" md = nil # match data # $stderr.puts "'#{x}'.Money_rep(#{self})" # Parse time. time = nil if (md = /(\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z)/.match(x)) time = Time.xmlschema(md[1]) unless time raise Currency::Exception::InvalidMoneyString, [ "time: #{str.inspect} #{currency} #{x.inspect}", :string, str, :currency, currency, :state, x, ] end x = md.pre_match + md.post_match end + # Default time time ||= @time time = Time.new if time == :now # $stderr.puts "x = #{x}" convert_currency = nil # Handle currency code in string. if (md = /([A-Z][A-Z][A-Z])/.match(x)) curr = ::Currency::Currency.get(md[1]) x = md.pre_match + md.post_match if @currency && @currency != curr if @enforce_currency raise ::Currency::Exception::IncompatibleCurrency, [ "currency: #{str.inspect} #{@currency.code}", :string, str, :default_currency, @currency, :parsed_currency, curr, ] end convert_currency = @currency end currency = curr else currency = @currency || ::Currency::Currency.default currency = ::Currency::Currency.get(currency) end # Remove placeholders and symbol. x = x.gsub(/[, ]/, '') symbol = currency.symbol # FIXME x = x.gsub(symbol, '') if symbol # $stderr.puts "x = #{x.inspect}" # Match: whole Currency value. if md = /^([-+]?\d+)\.?$/.match(x) # $stderr.puts "'#{self}'.parse(#{str}) => EXACT" x = ::Currency::Money.new_rep(md[1].to_i * currency.scale, currency, @time) - + # Match: fractional Currency value. elsif md = /^([-+]?)(\d*)\.(\d+)$/.match(x) sign = md[1] whole = md[2] part = md[3] - + # $stderr.puts "'#{self}'.parse(#{str}) => DECIMAL (#{sign} #{whole} . #{part})" - + if part.length != currency.scale - + # Pad decimal places with additional '0' while part.length < currency.scale_exp part << '0' end - + # Truncate to Currency's decimal size. part = part[0 ... currency.scale_exp] - + # $stderr.puts " => INEXACT DECIMAL '#{whole}'" end - + # Put the string back together: # #{sign}#{whole}#{part} whole = sign + whole + part # $stderr.puts " => REP = #{whole}" - + x = whole.to_i - + x = ::Currency::Money.new_rep(x, currency, time) else # $stderr.puts "'#{self}'.parse(#{str}) => ??? '#{x}'" #x.to_f.Money_rep(self) raise ::Currency::Exception::InvalidMoneyString, [ "#{str.inspect} #{currency} #{x.inspect}", :string, str, :currency, currency, :state, x, ] end # Do conversion. if convert_currency x = x.convert(convert_currency) end x end @@empty_hash = { } @@empty_hash.freeze # Parse a Money string in this Currency. # # "123.45".money # Using default Currency. # => USD $123.45 # # "$123.45 USD".money # Explicit Currency. # => USD $123.45 # # "CAD 123.45".money # => CAD $123.45 # # "123.45 CAD".money(:USD) # Incompatible explicit Currency. # !!! "123.45 CAD" USD (Currency::Exception::IncompatibleCurrency) # def parse(str, opt = @@empty_hash) prs = self unless opt.empty? prs = prs.clone opt.each_pair{ | k, v | prs.send("#{k}=", v) } end prs._parse(str) end end # class diff --git a/spec/money_spec.rb b/spec/money_spec.rb index 73d0fd1..02f8e39 100644 --- a/spec/money_spec.rb +++ b/spec/money_spec.rb @@ -1,347 +1,367 @@ require File.dirname(__FILE__) + '/spec_helper' # require File.dirname(__FILE__) + '/../lib/currency/formatter' describe Currency::Money do - it "create" do + before :all do + Currency::Config.configure do |config| + config.scale_exp = 6 + end + + end + + def zero_money + @zero_money ||= Currency::Money.new(0) + end + + def negative_money + @negative_money ||= Currency::Money.new(-1.00, :USD) + end + + def positive_money + @positive_money ||= Currency::Money.new(2.99, :USD) + end + + it "creates Monies" do m = Currency::Money.new(1.99) m.should be_kind_of(Currency::Money) Currency::Currency.default.should == m.currency :USD.should == m.currency.code end - describe "object money method" do + describe "Converts different objects to Money with the 'money' method" do it "works with a float" do m = 1.99.money(:USD) m.should be_kind_of(Currency::Money) :USD.should == m.currency.code m.rep.should == 1990000 end it "works with a FixNum" do m = 199.money(:CAD) m.should be_kind_of(Currency::Money) :CAD.should == m.currency.code m.rep.should == 199000000 end it "works with a string" do m = "13.98".money(:CAD) m.should be_kind_of(Currency::Money) :CAD.should == m.currency.code m.rep.should == 13980000 end it "works with a string again" do m = "45.99".money(:EUR) m.should be_kind_of(Currency::Money) :EUR.should == m.currency.code m.rep.should == 45990000 end + + describe "deals with voids" do + it "does not raise with an empty string" do + lambda{ + Currency::Money.new('') + }.should_not raise_error + end + + it "considers the empty string to be nil " do + Currency::Money.new('').should be_nil + end + end end - def zero_money - @zero_money ||= Currency::Money.new(0) - end - - it "zero" do + it "deals with zero in the least surprising way" do zero_money.negative?.should_not == true zero_money.zero?.should_not == nil zero_money.positive?.should_not == true end - def negative_money - @negative_money ||= Currency::Money.new(-1.00, :USD) - end - - it "negative" do + it "deals with negatives in the least surprising way" do negative_money.negative?.should_not == nil negative_money.zero?.should_not == true negative_money.positive?.should_not == true end - def positive_money - @positive_money ||= Currency::Money.new(2.99, :USD) - end - it "positive" do + it "deals with positive numbers in the least surprising way" do positive_money.negative?.should_not == true positive_money.zero?.should_not == true positive_money.positive?.should_not == nil end - it "relational" do + it "can do comparisons between monies" do n = negative_money z = zero_money p = positive_money - (n.should < p) - (n > p).should_not == true - (p < n).should_not == true + negative_money.should < positive_money + (negative_money > positive_money).should_not be_true + (positive_money < negative_money).should_not be_true (p.should > n) (p != n).should_not == nil (z.should <= z) (z.should >= z) (z.should <= p) (n.should <= z) (z.should >= n) n.should == n p.should == p z.should == zero_money end it "compare" do n = negative_money z = zero_money p = positive_money (n <=> p).should == -1 (p <=> n).should == 1 (p <=> z).should == 1 (n <=> n).should == 0 (z <=> z).should == 0 (p <=> p).should == 0 end it "rep" do m = Currency::Money.new(123, :USD) m.should_not == nil m.rep.should == 123000000 m = Currency::Money.new(123.45, :USD) m.should_not == nil m.rep.should == 123450000 m = Currency::Money.new("123.456", :USD) m.should_not == nil m.rep.should == 123456000 end it "convert" do m = Currency::Money.new("123.456", :USD) m.should_not == nil m.rep.should == 123456000 m.to_i.should == 123 m.to_f.should == 123.456 m.to_s.should == "$123.456000" end it "eql" do usd1 = Currency::Money.new(123, :USD) usd1.should_not == nil usd2 = Currency::Money.new("123", :USD) usd2.should_not == nil usd1.currency.code.should == :USD usd2.currency.code.should == :USD usd2.rep.should == usd1.rep usd1.should == usd2 end it "not eql" do usd1 = Currency::Money.new(123, :USD) usd1.should_not == nil usd2 = Currency::Money.new("123.01", :USD) usd2.should_not == nil usd1.currency.code.should == :USD usd2.currency.code.should == :USD usd2.rep.should_not == usd1.rep (usd1 != usd2).should_not == nil ################ # currency != # rep == usd = Currency::Money.new(123, :USD) usd.should_not == nil cad = Currency::Money.new(123, :CAD) cad.should_not == nil usd.currency.code.should == :USD cad.currency.code.should == :CAD cad.rep.should == usd.rep (usd.currency != cad.currency).should_not == nil (usd != cad).should_not == nil end describe "operations" do before(:each) do @usd = Currency::Money.new(123.45, :USD) @cad = Currency::Money.new(123.45, :CAD) end it "should work" do @usd.should_not == nil @cad.should_not == nil end it "handle negative money" do # - Currency::Money => Currency::Money (- @usd).rep.should == -123450000 (- @usd).currency.code.should == :USD (- @cad).rep.should == -123450000 (- @cad).currency.code.should == :CAD end it "should add monies of the same currency" do m = (@usd + @usd) m.should be_kind_of(Currency::Money) m.rep.should == 246900000 m.currency.code.should == :USD end it "should add monies of different currencies and return USD" do m = (@usd + @cad) m.should be_kind_of(Currency::Money) m.rep.should == 228890724 m.currency.code.should == :USD end it "should add monies of different currencies and return CAD" do m = (@cad + @usd) m.should be_kind_of(Currency::Money) m.rep.should == 267985260 m.currency.code.should == :CAD end it "should subtract monies of the same currency" do m = (@usd - @usd) m.should be_kind_of(Currency::Money) m.rep.should == 0 m.currency.code.should == :USD end it "should subtract monies of different currencies and return USD" do m = (@usd - @cad) m.should be_kind_of(Currency::Money) m.rep.should == 18009276 m.currency.code.should == :USD end it "should subtract monies of different currencies and return CAD" do m = (@cad - @usd) m.should be_kind_of(Currency::Money) m.rep.should == -21085260 m.currency.code.should == :CAD end it "should multiply by numerics and return money" do m = (@usd * 0.5) m.should be_kind_of(Currency::Money) m.rep.should == 61725000 m.currency.code.should == :USD end it "should divide by numerics and return money" do m = @usd / 3 m.should be_kind_of(Currency::Money) m.rep.should == 41150000 m.currency.code.should == :USD end it "should divide by monies of the same currency and return numeric" do m = @usd / Currency::Money.new("41.15", :USD) m.should be_kind_of(Numeric) m.should be_close(3.0, 1.0e-8) end it "should divide by monies of different currencies and return numeric" do m = (@usd / @cad) m.should be_kind_of(Numeric) m.should be_close(Currency::Exchange::Rate::Source::Test.USD_CAD, 0.0001) end end it "pivot conversions" do # Using default get_rate cad = Currency::Money.new(123.45, :CAD) cad.should_not == nil eur = cad.convert(:EUR) eur.should_not == nil m = (eur.to_f / cad.to_f) m.should be_kind_of(Numeric) m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_CAD) * Currency::Exchange::Rate::Source::Test.USD_EUR m.should be_close(m_expected, 0.001) gbp = Currency::Money.new(123.45, :GBP) gbp.should_not == nil eur = gbp.convert(:EUR) eur.should_not == nil m = (eur.to_f / gbp.to_f) m.should be_kind_of(Numeric) m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_GBP) * Currency::Exchange::Rate::Source::Test.USD_EUR m.should be_close(m_expected, 0.001) end it "invalid currency code" do lambda {Currency::Money.new(123, :asdf)}.should raise_error(Currency::Exception::InvalidCurrencyCode) lambda {Currency::Money.new(123, 5)}.should raise_error(Currency::Exception::InvalidCurrencyCode) end it "time default" do Currency::Money.default_time = nil usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should == nil Currency::Money.default_time = Time.now usd = Currency::Money.new(123.45, :USD) usd.should_not == nil Currency::Money.default_time.should == usd.time end it "time now" do Currency::Money.default_time = :now usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should_not == nil sleep 1 usd2 = Currency::Money.new(123.45, :USD) usd2.should_not == nil usd2.time.should_not == nil (usd.time != usd2.time).should_not == nil Currency::Money.default_time = nil end it "time fixed" do Currency::Money.default_time = Time.new usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should_not == nil sleep 1 usd2 = Currency::Money.new(123.45, :USD) usd2.should_not == nil usd2.time.should_not == nil usd.time.should == usd2.time end end diff --git a/spec/parser_spec.rb b/spec/parser_spec.rb index f4fc32f..26cd9de 100644 --- a/spec/parser_spec.rb +++ b/spec/parser_spec.rb @@ -1,105 +1,105 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. +require File.dirname(__FILE__) + '/spec_helper' -require 'test/test_base' -require 'currency' - -module Currency - -class ParserTest < TestBase +describe Currency::Parser do before do - super @parser = ::Currency::Currency.USD.parser_or_default end - ############################################ - # Simple stuff. - # - - it "default" do - + describe "is great at parsing strings" do + it "can use a string that uses the thousands-separator (comma)" do + @parser.parse("1234567.89").rep.should == 123456789 + @parser.parse("1,234,567.89").rep.should == 123456789 + end + + + it "parses cents" do + @parser.parse("1234567.89").rep.should == 123456789 + @parser.parse("1234567").rep.should == 123456700 + @parser.parse("1234567.").rep.should == 123456700 + @parser.parse("1234567.8").rep.should == 123456780 + @parser.parse("1234567.891").rep.should == 123456789 + @parser.parse("-1234567").rep.should == -123456700 + @parser.parse("+1234567").rep.should == 123456700 + end end - - it "thousands" do - @parser.parse("1234567.89").rep.should == 123456789 - assert_equal 123456789, @parser.parse("1,234,567.89").rep + describe "can convert the right hand side argument" do + it "converts the right hand argument to the left hand side currency if needed" do + m = "123.45 USD".money + "100 CAD" + m.should_not == nil + m.rep.should == ("123.45".money(:USD) + "100 CAD".money(:USD)).rep + end + + it "uses the left hand sides currency if the right hand side argument does provide currency info" do + m = "123.45 USD".money + (m + 100).rep.should == (m + "100".money(:USD)).rep + end end + describe "can use the inspect method as a serialization of self" do + it "can recreate a money object by using a .inspect-string" do + ::Currency::Currency.default = :USD + m = ::Currency::Money("1234567.89", :CAD) + m2 = ::Currency::Money(m.inspect) - it "cents" do - @parser.parse("1234567.89").rep.should == 123456789 - @parser.parse("1234567").rep.should == 123456700 - @parser.parse("1234567.").rep.should == 123456700 - @parser.parse("1234567.8").rep.should == 123456780 - @parser.parse("1234567.891").rep.should == 123456789 - @parser.parse("-1234567").rep.should == -123456700 - @parser.parse("+1234567").rep.should == 123456700 - end + m2.rep.should == m.rep + m2.currency.should == m.currency + m2.inspect.should == m.inspect + end - it "misc" do - m = "123.45 USD".money + "100 CAD".should_not == nil - (m.rep == 200.45).should_not == true - end + it "can recreate a money objectby using a .inspect-string and keep the time parameter as well" do + ::Currency::Currency.default = :USD + time = Time.now.getutc + m = ::Currency::Money("1234567.89", :CAD, time) + m.time.should_not == nil - it "round trip" do - ::Currency::Currency.default = :USD - m = ::Currency::Money("1234567.89", :CAD).should_not == nil - m2 = ::Currency::Money(m.inspect).should_not == nil - m2.rep.should == m.rep - m2.currency.should == m.currency - m2.time.should == nil - m2.inspect.should == m.inspect - end + m2 = ::Currency::Money(m.inspect) + m2.time.should_not == nil + m.should_not be(m2) - it "round trip time" do - ::Currency::Currency.default = :USD - time = Time.now.getutc - m = ::Currency::Money("1234567.89", :CAD, time).should_not == nil - m.time.should_not == nil - m2 = ::Currency::Money(m.inspect).should_not == nil - m2.time.should_not == nil - m2.rep.should == m.rep - m2.currency.should == m.currency - m2.time.to_i.should == m.time.to_i - m2.inspect.should == m.inspect + m2.rep.should == m.rep + m2.currency.should == m.currency + m2.time.to_i.should == m.time.to_i + m2.inspect.should == m.inspect + end end + describe "deals with time when creating money objects" do + before do + @parser = ::Currency::Parser.new + end + + it "can parse even though the parser time is nil" do + @parser.time = nil - it "time nil" do - parser = ::Currency::Parser.new - parser.time = nil + m = @parser.parse("$1234.55") + m.time.should == nil + end - m = parser.parse("$1234.55").should_not == nil - m.time.should == nil - end + it "parses money strings into money object using the parsers time" do + @parser.time = Time.now - it "time" do - parser = ::Currency::Parser.new - parser.time = Time.new + m = @parser.parse("$1234.55") + m.time.should == @parser.time + end - m = parser.parse("$1234.55").should_not == nil - m.time.should == parser.time - end + it "when re-initializing a money object, the time is also re-initialized" do + @parser.time = :now - it "time now" do - parser = ::Currency::Parser.new - parser.time = :now + m = @parser.parse("$1234.55") + m1_time = m.time - m = parser.parse("$1234.55").should_not == nil - m1_time = m.time.should_not == nil + m = @parser.parse("$1234.55") + m2_time = m.time - m = parser.parse("$1234.55").should_not == nil - m2_time = m.time.should_not == nil - - assert_not_equal m1_time, m2_time + m1_time.should_not == m2_time + end end end - -end # module -
acvwilson/currency
7cd4230abbf3b6373282903dae729ded6c81ae18
Changed: custom exceptions to inherit from StandardError instead of the root Exception class so that they can be rescued without needing to explicitly declare the exception in the rescue
diff --git a/lib/currency/exception.rb b/lib/currency/exception.rb index 9fdedfd..734bc1f 100644 --- a/lib/currency/exception.rb +++ b/lib/currency/exception.rb @@ -1,119 +1,119 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. module Currency::Exception # Base class for all Currency::Exception objects. # # raise Currency::Exception [ "msg", :opt1, 1, :opt2, 2 ] # - class Base < ::Exception + class Base < ::StandardError EMPTY_HASH = { }.freeze def initialize(arg1, *args) case arg1 # [ description, ... ] when Array @opts = arg1 arg1 = arg1.shift else @opts = nil end case @opts when Array if @opts.size == 1 && @opts.first.kind_of?(Hash) # [ description, { ... } ] @opts = @opts.first else # [ description, :key, value, ... ] @opts = Hash[*@opts] end end case @opts when Hash @opts = @opts.dup.freeze else @opts = { :info => @opts }.freeze end @opts ||= EMPTY_HASH super(arg1, *args) end def method_missing(sel, *args, &blk) sel = sel.to_sym if args.empty? && ! block_given? && @opts.key?(sel) return @opts[sel] end super end def to_s super + ": #{@opts.inspect}" end end # Generic Error. class Generic < Base end # Error during parsing of Money values from String. class InvalidMoneyString < Base end # Error during coercion of external Money values. class InvalidMoneyValue < Base end # Error in Currency code formeat. class InvalidCurrencyCode < Base end # Error during conversion between currencies. class IncompatibleCurrency < Base end # Error during locating currencies. class MissingCurrency < Base end # Error if an Exchange is not defined. class UndefinedExchange < Base end # Error if a Currency is unknown. class UnknownCurrency < Base end # Error if an Exchange Rate Source cannot provide an Exchange::Rate. class UnknownRate < Base end # Error if an Exchange Rate Source. class RateSourceError < Base end # Error if an Exchange Rate Source cannot supply any rates. class UnavailableRates < Base end # Error if an Exchange::Rate is not valid. class InvalidRate < Base end # Error if a subclass is responsible for implementing a method. class SubclassResponsibility < Base end # Error if some functionality is unimplemented class Unimplemented < Base end # Error if reentrantancy is d class InvalidReentrancy < Base end end # module
acvwilson/currency
522bb413515e936604eb7324e8e628de200a53bd
Changed: gemname to be correct
diff --git a/currency.gemspec b/currency.gemspec index a870aee..02f1d38 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| - s.name = %q{acvwilson-currency} + s.name = %q{currency} s.version = "0.6.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] s.date = %q{#{Date.today}} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/currency_version.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} s.summary = %q{#{s.name} #{s.version}} end \ No newline at end of file
acvwilson/currency
b39dc512c72192dc8afc688bcb268eba0fddbe62
CHANGED: bumped version number CHANGED: refactoring of configuration madness initiated (not complete): removed Threading code CHANGED: scale is now configurable CHANGED: can reset cached currencies when needed (e.g. when the scale changes) CHANGED: added a default scale of 2 CHANGED: removed cruft and misc cleanups CHANGED: removed hardcoded scale in Factory
diff --git a/currency.gemspec b/currency.gemspec index 45a98a0..a870aee 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| - s.name = %q{currency} - s.version = "0.5.2" + s.name = %q{acvwilson-currency} + s.version = "0.6.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] - s.date = %q{2008-11-14} + s.date = %q{#{Date.today}} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] - s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/currency_version.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_core_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] + s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/currency_version.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_spec_helper.rb", "spec/ar_column_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} - s.summary = %q{currency 0.5.2} + s.summary = %q{#{s.name} #{s.version}} end \ No newline at end of file diff --git a/lib/currency/config.rb b/lib/currency/config.rb index afc4134..bb2ef87 100644 --- a/lib/currency/config.rb +++ b/lib/currency/config.rb @@ -1,91 +1,93 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # The Currency::Config class is responsible for # maintaining global configuration for the Currency package. # # TO DO: # # Migrate all class variable configurations to this object. +# Rewrite this whole class. It is not working at all after first config +# Threads are bad. Use the Singleton library when rewriting this class Currency::Config - @@default = nil - # Returns the default Currency::Config object. # # If one is not specfied an instance is # created. This is a global, not thread-local. def self.default - @@default ||= - self.new + @@default ||= self.new end # Sets the default Currency::Config object. def self.default=(x) @@default = x + Currency::Currency::Factory.reset + @@default end - # Returns the current Currency::Config object used during - # in the current thread. - # + # Returns the current Currency::Config object # If #current= has not been called and #default= has not been called, # then UndefinedExchange is raised. def self.current - Thread.current[:Currency__Config] ||= - self.default || - (raise ::Currency::Exception::UndefinedConfig, "Currency::Config.default not defined") + self.default || (raise ::Currency::Exception::UndefinedConfig, "Currency::Config.default not defined") end # Sets the current Currency::Config object used # in the current thread. def self.current=(x) - Thread.current[:Currency__Config] = x + self.default = x end # Clones the current configuration and makes it current # during the execution of a block. After block completes, # the previous configuration is restored. # # Currency::Config.configure do | c | # c.float_ref_filter = Proc.new { | x | x.round } # "123.448".money.rep == 12345 # end + # TODO: rewrite from scratch def self.configure(&blk) c_prev = current c_new = self.current = current.clone result = nil begin result = yield c_new - ensure + rescue self.current = c_prev end result end - @@identity = Proc.new { |x| x } # :nodoc: - # Returns the current Float conversion filter. # Can be used to set rounding or truncation policies when converting # Float values to Money values. # Defaults to an identity function. # See Float#Money_rep. + attr_accessor :float_ref_filter def float_ref_filter - @float_ref_filter ||= - @@identity - end - - # Sets the current Float conversion filter. - def float_ref_filter=(x) - @float_ref_filter = x + @float_ref_filter ||= Proc.new { |x| x } end - # Defines the table name for Historical::Rate records. # Defaults to 'currency_historical_rates'. attr_accessor :historical_table_name def historical_table_name @historical_table_name ||= 'currency_historical_rates' end + + attr_accessor :scale_exp + def scale_exp=(val) + raise ArgumentError, "Invalid scale exponent" unless val.integer? + raise ArgumentError, "Invalid scale: zero" if val.zero? + @scale_exp = val + Currency::Currency::Factory.reset + end -end # module - + attr_reader :scale + def scale + 10 ** (scale_exp || 2) + end + +end \ No newline at end of file diff --git a/lib/currency/core_extensions.rb b/lib/currency/core_extensions.rb index 47d3d68..686759c 100644 --- a/lib/currency/core_extensions.rb +++ b/lib/currency/core_extensions.rb @@ -1,83 +1,33 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. - - class Object # Exact conversion to Money representation value. def money(*opts) Currency::Money(self, *opts) end end - - class Integer # Exact conversion to Money representation value. def Money_rep(currency, time = nil) Integer(self * currency.scale) end end -# module Asa -# module Rounding -# def self.included(base) #:nodoc: -# puts "included by #{base.inspect}" -# base.class_eval do -# alias_method :round_without_precision, :round -# alias_method :round, :round_with_precision -# end -# end -# -# # Rounds the float with the specified precision. -# # -# # x = 1.337 -# # x.round # => 1 -# # x.round(1) # => 1.3 -# # x.round(2) # => 1.34 -# def round_with_precision(precision = nil) -# precision.nil? ? round_without_precision : (self * (10 ** precision)).round / (10 ** precision).to_f -# end -# -# end -# end -# -# class Float -# include Asa::Rounding -# # Inexact conversion to Money representation value. -# def Money_rep(currency, time = nil) -# Integer(Currency::Config.current.float_ref_filter.call(self * currency.scale)) -# end -# end - class Float # Inexact conversion to Money representation value. def Money_rep(currency, time = nil) Integer(Currency::Config.current.float_ref_filter.call(self * currency.scale)) end - - # def round_with_awesome_precision(precision = nil) - # # puts "self: #{self.inspect}" - # # puts "precision: #{precision.inspect}" - # # puts "round_without_precision: #{round_without_precision.inspect}" - # # puts "self * (10 ** precision): #{(self * (10 ** precision)).inspect}" - # # puts "(self * (10 ** precision)).round_without_precision: #{((self * (10 ** precision)).round_without_precision).inspect}" - # # self.to_s.to_f.round_without_precision - # precision.nil? ? round_without_awesome_precision : (self * (10 ** precision)).round_without_awesome_precision / (10 ** precision).to_f - # end - # alias_method :round_without_awesome_precision, :round - # alias_method :round, :round_with_awesome_precision end - - - class String # Exact conversion to Money representation value. def Money_rep(currency, time = nil) x = currency.parse(self, :currency => currency, :time => time) x = x.rep if x.respond_to?(:rep) x end end diff --git a/lib/currency/currency.rb b/lib/currency/currency.rb index 0e6ced4..0d8e79d 100644 --- a/lib/currency/currency.rb +++ b/lib/currency/currency.rb @@ -1,175 +1,172 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # Represents a currency. # # Currency objects are created on-demand by Currency::Currency::Factory. # # See Currency.get method. # class Currency::Currency # Returns the ISO three-letter currency code as a symbol. # e.g. :USD, :CAD, etc. attr_reader :code # The Currency's scale factor. # e.g: the :USD scale factor is 100. attr_reader :scale # The Currency's scale factor. # e.g: the :USD scale factor is 2, where 10 ^ 2 == 100. attr_reader :scale_exp # Used by Formatter. attr_reader :format_right # Used by Formatter. attr_reader :format_left # The Currency's symbol. # e.g: USD symbol is '$' attr_accessor :symbol # The Currency's symbol as HTML. # e.g: EUR symbol is '&#8364;' (:html &#8364; :) or '&euro;' (:html &euro; :) attr_accessor :symbol_html # The default Formatter. attr_accessor :formatter # The default parser. attr_accessor :parser # Create a new currency. # This should only be called from Currency::Currency::Factory. - def initialize(code, symbol = nil, scale = 1000000) + # def initialize(code, symbol = nil, scale = 1000000) + def initialize(code, symbol = nil, scale = Currency::Config.current.scale) self.code = code self.symbol = symbol self.scale = scale - - @formatter = - @parser = - nil end # Returns the Currency object from the default Currency::Currency::Factory # by its three-letter uppercase Symbol, such as :USD, or :CAD. def self.get(code) # $stderr.puts "#{self}.get(#{code.inspect})" return nil unless code return code if code.kind_of?(::Currency::Currency) Factory.default.get_by_code(code) end # Internal method for converting currency codes to internal # Symbol format. def self.cast_code(x) x = x.upcase.intern if x.kind_of?(String) raise ::Currency::Exception::InvalidCurrencyCode, x unless x.kind_of?(Symbol) raise ::Currency::Exception::InvalidCurrencyCode, x unless x.to_s.length == 3 x end # Returns the hash of the Currency's code. def hash @code.hash end # Returns true if the Currency's are equal. def eql?(x) self.class == x.class && @code == x.code end # Returns true if the Currency's are equal. def ==(x) self.class == x.class && @code == x.code end # Clients should never call this directly. def code=(x) x = self.class.cast_code(x) unless x.nil? @code = x #$stderr.puts "#{self}.code = #{@code}"; x end # Clients should never call this directly. def scale=(x) @scale = x return x if x.nil? @scale_exp = Integer(Math.log10(@scale)); @format_right = - @scale_exp @format_left = @format_right - 1 x end # Parse a Money string in this Currency. # # See Currency::Parser#parse. # def parse(str, *opt) parser_or_default.parse(str, *opt) end def parser_or_default (@parser || ::Currency::Parser.default) end # Formats the Money value as a string using the current Formatter. # See Currency::Formatter#format. def format(m, *opt) formatter_or_default.format(m, *opt) end def formatter_or_default (@formatter || ::Currency::Formatter.default) end # Returns the Currency code as a String. def to_s @code.to_s end # Returns the default Factory's currency. def self.default Factory.default.currency end # Sets the default Factory's currency. def self.default=(x) x = self.get(x) unless x.kind_of?(self) Factory.default.currency = x end # If selector is [A-Z][A-Z][A-Z], load the currency via Factory.default. # # Currency::Currency.USD # => #<Currency::Currency:0xb7d0917c @formatter=nil, @scale_exp=2, @scale=100, @symbol="$", @format_left=-3, @code=:USD, @parser=nil, @format_right=-2> # def self.method_missing(sel, *args, &blk) if args.size == 0 && (! block_given?) && /^[A-Z][A-Z][A-Z]$/.match(sel.to_s) Factory.default.get_by_code(sel) else super end end end # class diff --git a/lib/currency/currency/factory.rb b/lib/currency/currency/factory.rb index ede1cd1..6cb1228 100644 --- a/lib/currency/currency/factory.rb +++ b/lib/currency/currency/factory.rb @@ -1,121 +1,131 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # Responsible for creating Currency::Currency objects on-demand. class Currency::Currency::Factory @@default = nil # Returns the default Currency::Factory. def self.default @@default ||= self.new end # Sets the default Currency::Factory. def self.default=(x) @@default = x end def initialize(*opts) @currency_by_code = { } @currency_by_symbol = { } @currency = nil end + def self.reset + default.reset + end + + def reset + @currency_by_code = { } + @currency_by_symbol = { } + @currency = nil + end + # Lookup Currency by code. def get_by_code(x) x = ::Currency::Currency.cast_code(x) # $stderr.puts "get_by_code(#{x})" @currency_by_code[x] ||= install(load(::Currency::Currency.new(x))) end # Lookup Currency by symbol. def get_by_symbol(symbol) @currency_by_symbol[symbol] ||= install(load(::Currency::Currency.new(nil, symbol))) end # This method initializes a Currency object as # requested from #get_by_code or #get_by_symbol. # # This method must initialize: # # currency.code # currency.scale # # Optionally: # # currency.symbol # currency.symbol_html # # Subclasses that provide Currency metadata should override this method. # For example, loading Currency metadata from a database or YAML file. def load(currency) # $stderr.puts "BEFORE: load(#{currency.code})" # Basic if currency.code == :USD || currency.symbol == '$' # $stderr.puts "load('USD')" currency.code = :USD currency.symbol = '$' - currency.scale = 1000000 + # currency.scale = 1000000 elsif currency.code == :CAD # $stderr.puts "load('CAD')" currency.symbol = '$' - currency.scale = 1000000 + # currency.scale = 1000000 elsif currency.code == :EUR # $stderr.puts "load('CAD')" currency.symbol = nil currency.symbol_html = '&#8364;' - currency.scale = 1000000 + # currency.scale = 1000000 else currency.symbol = nil - currency.scale = 1000000 + # currency.scale = 1000000 end # $stderr.puts "AFTER: load(#{currency.inspect})" currency end # Installs a new Currency for #get_by_symbol and #get_by_code. def install(currency) raise ::Currency::Exception::UnknownCurrency unless currency @currency_by_symbol[currency.symbol] ||= currency unless currency.symbol.nil? @currency_by_code[currency.code] = currency end # Returns the default Currency. # Defaults to self.get_by_code(:USD). def currency @currency ||= self.get_by_code(:USD) end # Sets the default Currency. def currency=(x) @currency = x end # If selector is [A-Z][A-Z][A-Z], load the currency. # # factory.USD # => #<Currency::Currency:0xb7d0917c @formatter=nil, @scale_exp=2, @scale=100, @symbol="$", @format_left=-3, @code=:USD, @parser=nil, @format_right=-2> # def method_missing(sel, *args, &blk) if args.size == 0 && (! block_given?) && /^[A-Z][A-Z][A-Z]$/.match(sel.to_s) self.get_by_code(sel) else super end end end # class diff --git a/lib/currency/formatter.rb b/lib/currency/formatter.rb index b12da1d..5bdb502 100644 --- a/lib/currency/formatter.rb +++ b/lib/currency/formatter.rb @@ -1,310 +1,308 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'rss/rss' # Time#xmlschema # This class formats a Money value as a String. # Each Currency has a default Formatter. class Currency::Formatter # The underlying object for Currency::Formatter#format. # This object is cloned and initialized with strings created # from Formatter#format. # It handles the Formatter#format string interpolation. class Template @@empty_hash = { } @@empty_hash.freeze # The template string. attr_accessor :template # The Currency::Money object being formatted. attr_accessor :money # The Currency::Currency object being formatted. attr_accessor :currency # The sign: '-' or nil. attr_accessor :sign # The whole part of the value, with thousands_separator or nil. attr_accessor :whole # The fraction part of the value, with decimal_separator or nil. attr_accessor :fraction # The currency symbol or nil. attr_accessor :symbol # The currency code or nil. attr_accessor :code # The time or nil. attr_accessor :time def initialize(opts = @@empty_hash) @template = @template_proc = nil opts.each_pair{ | k, v | self.send("#{k}=", v) } end # Sets the template string and uncaches the template_proc. def template=(x) if @template != x @template_proc = nil end @template = x end # Defines a the self._format template procedure using # the template as a string to be interpolated. def template_proc(template = @template) return @template_proc if @template_proc @template_proc = template || '' # @template_proc = @template_proc.gsub(/[\\"']/) { | x | "\\" + x } @template_proc = "def self._format; \"#{@template_proc}\"; end" self.instance_eval @template_proc @template_proc end # Formats the current state using the template. def format template_proc _format end end # Defaults to ',' attr_accessor :thousands_separator # Defaults to '.' attr_accessor :decimal_separator # If true, insert _thousands_separator_ between each 3 digits in the whole value. attr_accessor :thousands # If true, append _decimal_separator_ and decimal digits after whole value. attr_accessor :cents # If true, prefix value with currency symbol. attr_accessor :symbol # If true, append currency code. attr_accessor :code # If true, append the time. attr_accessor :time # The number of fractional digits in the time. # Defaults to 4. attr_accessor :time_fractional_digits # If true, use html formatting. # # Currency::Money(12.45, :EUR).to_s(:html => true; :code => true) # => "&#8364;12.45 <span class=\"currency_code\">EUR</span>" attr_accessor :html # A template string used to format a money value. # Defaults to: # # '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}#{time && " "}#{time}' attr_accessor :template # Set the decimal_places # Defaults to: nil attr_accessor :decimals # If passed true, formats for an input field (i.e.: as a number). def as_input_value=(x) if x self.thousands_separator = '' self.decimal_separator = '.' self.thousands = false self.cents = true self.symbol = false self.code = false self.html = false self.time = false self.time_fractional_digits = nil end x end @@default = nil # Get the default Formatter. def self.default @@default || self.new end # Set the default Formatter. def self.default=(x) @@default = x end def initialize(opt = { }) @thousands_separator = ',' @decimal_separator = '.' @thousands = true @cents = true @symbol = true @code = false @html = false @time = false @time_fractional_digits = 4 @template = '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}#{time && " "}#{time}' @template_object = nil @decimals = nil opt.each_pair{ | k, v | self.send("#{k}=", v) } end def currency=(x) # :nodoc: # DO NOTHING! end # Sets the template and the Template#template. def template=(x) if @template_object @template_object.template = x end @template = x end # Returns the Template object. def template_object return @template_object if @template_object @template_object = Template.new @template_object.template = @template if @template # $stderr.puts "template.template = #{@template_object.template.inspect}" @template_object.template_proc # pre-cache before clone. @template_object end def _format(m, currency = nil, time = nil) # :nodoc: # Get currency. currency ||= m.currency # Get time. time ||= m.time # set decimal places @decimals ||= currency.scale_exp # Setup template tmpl = self.template_object.clone # $stderr.puts "template.template = #{tmpl.template.inspect}" tmpl.money = m tmpl.currency = currency # Get scaled integer representation for this Currency. # $stderr.puts "m.currency = #{m.currency}, currency => #{currency}" x = m.Money_rep(currency) # Remove sign. x = - x if ( neg = x < 0 ) tmpl.sign = neg ? '-' : nil # Convert to String. x = x.to_s # Keep prefixing "0" until filled to scale. while ( x.length <= currency.scale_exp ) x = "0" + x end # Insert decimal place. whole = x[0 .. currency.format_left] fraction = x[currency.format_right .. -1] # Round the fraction to the supplied number of decimal places fraction = (fraction.to_f / currency.scale).round(@decimals).to_s[2..-1] # raise "decimals: #{@decimals}, scale_exp: #{currency.scale_exp}, x is: #{x.inspect}, currency.scale_exp is #{currency.scale_exp.inspect}, fraction: #{fraction.inspect}" while ( fraction.length < @decimals ) fraction = fraction + "0" end # raise "x is: #{x.inspect}, currency.scale_exp is #{currency.scale_exp.inspect}, fraction: #{fraction.inspect}" # fraction = ((fraction.to_f / currency.scale).round(decimals) * (10 ** decimals)).to_i.to_s # Do thousands. x = whole if @thousands && (@thousands_separator && ! @thousands_separator.empty?) x.reverse! x.gsub!(/(\d\d\d)/) {|y| y + @thousands_separator} x.sub!(/#{@thousands_separator}$/,'') x.reverse! end # Put whole and fractional parts. tmpl.whole = x tmpl.fraction = @cents && @decimal_separator ? @decimal_separator + fraction : nil # Add symbol? tmpl.symbol = @symbol ? ((@html && currency.symbol_html) || currency.symbol) : nil # Add currency code. tmpl.code = @code ? _format_Currency(currency) : nil # Add time. tmpl.time = @time && time ? _format_Time(time) : nil # Ask template to format the components. tmpl.format end def _format_Currency(c) # :nodoc: x = '' x << '<span class="currency_code">' if @html x << c.code.to_s x << '</span>' if @html x end def _format_Time(t) # :nodoc: x = '' x << t.getutc.xmlschema(@time_fractional_digits) if t x end @@empty_hash = { } @@empty_hash.freeze # Format a Money object as a String. # # m = Money.new("1234567.89") # m.to_s(:code => true, :symbol => false) # => "1,234,567.89 USD" # def format(m, opt = @@empty_hash) - # raise "huh: #{opt.inspect}" - fmt = self unless opt.empty? fmt = fmt.clone opt.each_pair{ | k, v | fmt.send("#{k}=", v) } end # $stderr.puts "format(opt = #{opt.inspect})" fmt._format(m, opt[:currency]) # Allow override of current currency. end end # class diff --git a/lib/currency/money.rb b/lib/currency/money.rb index b77d646..32b56f4 100644 --- a/lib/currency/money.rb +++ b/lib/currency/money.rb @@ -1,298 +1,293 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # # Represents an amount of money in a particular currency. # # A Money object stores its value using a scaled Integer representation # and a Currency object. # # A Money object also has a time, which is used in conversions # against historical exchange rates. # class Currency::Money include Comparable @@default_time = nil def self.default_time @@default_time end def self.default_time=(x) @@default_time = x end @@empty_hash = { } @@empty_hash.freeze # # DO NOT CALL THIS DIRECTLY: # # See Currency.Money() function. # # Construct a Money value object # from a pre-scaled external representation: # where x is a Float, Integer, String, etc. # # If a currency is not specified, Currency.default is used. # # x.Money_rep(currency) # # is invoked to coerce x into a Money representation value. # # For example: # # 123.Money_rep(:USD) => 12300 # # Because the USD Currency object has a #scale of 100 # # See #Money_rep(currency) mixin. # def initialize(x, currency = nil, time = nil) - opts ||= @@empty_hash - - # Set ivars. - currency = ::Currency::Currency.get(currency) - @currency = currency + @currency = ::Currency::Currency.get(currency) @time = time || ::Currency::Money.default_time @time = ::Currency::Money.now if @time == :now + if x.kind_of?(String) - if currency - m = currency.parser_or_default.parse(x, :currency => currency) + if @currency + m = @currency.parser_or_default.parse(x, :currency => @currency) else m = ::Currency::Parser.default.parse(x) end @currency = m.currency unless @currency @time = m.time if m.time @rep = m.rep else @currency = ::Currency::Currency.default unless @currency @rep = x.Money_rep(@currency) end end # Returns a Time.new # Can be modifed for special purposes. def self.now Time.new end # Compatibility with Money package. def self.us_dollar(x) self.new(x, :USD) end # Compatibility with Money package. def cents @rep end # Construct from post-scaled internal representation. def self.new_rep(r, currency = nil, time = nil) x = self.new(0, currency, time) x.set_rep(r) x end # Construct from post-scaled internal representation. # using the same currency. # # x = Currency.Money("1.98", :USD) # x.new_rep(123) => USD $1.23 # # time defaults to self.time. def new_rep(r, time = nil) time ||= @time x = self.class.new(0, @currency, time) x.set_rep(r) x end # Do not call this method directly. # CLIENTS SHOULD NEVER CALL set_rep DIRECTLY. # You have been warned in ALL CAPS. def set_rep(r) # :nodoc: r = r.to_i unless r.kind_of?(Integer) @rep = r end # Do not call this method directly. # CLIENTS SHOULD NEVER CALL set_time DIRECTLY. # You have been warned in ALL CAPS. def set_time(time) # :nodoc: @time = time end # Returns the Money representation (usually an Integer). def rep @rep end # Get the Money's Currency. def currency @currency end # Get the Money's time. def time @time end # Convert Money to another Currency. # currency can be a Symbol or a Currency object. # If currency is nil, the Currency.default is used. def convert(currency, time = nil) currency = ::Currency::Currency.default if currency.nil? currency = ::Currency::Currency.get(currency) unless currency.kind_of?(Currency) if @currency == currency self else time = self.time if time == :money ::Currency::Exchange::Rate::Source.current.convert(self, currency, time) end end # Hash for hash table: both value and currency. # See #eql? below. def hash @rep.hash ^ @currency.hash end # True if money values have the same value and currency. def eql?(x) self.class == x.class && @rep == x.rep && @currency == x.currency end # True if money values have the same value and currency. def ==(x) self.class == x.class && @rep == x.rep && @currency == x.currency end # Compares Money values. # Will convert x to self.currency before comparision. def <=>(x) if @currency == x.currency @rep <=> x.rep else @rep <=> convert(@currency, @time).rep end end # - Money => Money # # Negates a Money value. def -@ new_rep(- @rep) end # Money + (Money | Number) => Money # # Right side may be coerced to left side's Currency. def +(x) new_rep(@rep + x.Money_rep(@currency)) end # Money - (Money | Number) => Money # # Right side may be coerced to left side's Currency. def -(x) new_rep(@rep - x.Money_rep(@currency)) end # Money * Number => Money # # Right side must be Number. def *(x) new_rep(@rep * x) end # Money / Money => Float (ratio) # Money / Number => Money # # Right side must be Money or Number. # Right side Integers are not coerced to Float before # division. def /(x) if x.kind_of?(self.class) (@rep.to_f) / (x.Money_rep(@currency).to_f) else new_rep(@rep / x) end end # Formats the Money value as a String using the Currency's Formatter. def format(*opt) @currency.format(self, *opt) end # Formats the Money value as a String. def to_s(*opt) - # raise "huh: #{opt.inspect}" - @currency.format(self, *opt) end # Coerces the Money's value to a Float. # May cause loss of precision. def to_f Float(@rep) / @currency.scale end # Coerces the Money's value to an Integer. # May cause loss of precision. def to_i @rep / @currency.scale end # True if the Money's value is zero. def zero? @rep == 0 end # True if the Money's value is greater than zero. def positive? @rep > 0 end # True if the Money's value is less than zero. def negative? @rep < 0 end # Returns the Money's value representation in another currency. def Money_rep(currency, time = nil) # Attempt conversion? if @currency != currency || (time && @time != time) self.convert(currency, time).rep # raise ::Currency::Exception::Generic, "Incompatible Currency: #{@currency} != #{currency}" else @rep end end # Basic inspection, with symbol, currency code and time. # The standard #inspect method is available as #inspect_deep. def inspect(*opts) self.format(:symbol => true, :code => true, :time => true) end # How to alias a method defined in an object superclass in a different class: define_method(:inspect_deep, Object.instance_method(:inspect)) # How call a method defined in a superclass from a method with a different name: # def inspect_deep(*opts) # self.class.superclass.instance_method(:inspect).bind(self).call # end end # class diff --git a/spec/config_spec.rb b/spec/config_spec.rb index 0b910ce..424825d 100644 --- a/spec/config_spec.rb +++ b/spec/config_spec.rb @@ -1,29 +1,70 @@ require File.dirname(__FILE__) + '/spec_helper' describe Currency::Config do it "should truncate" do Currency::Config.configure do | c | c.float_ref_filter = Proc.new { | x | x } m = Currency::Money.new(1.999999999) m.should be_kind_of(Currency::Money) m.rep.should == 1999999 end end it "should round" do Currency::Config.configure do | c | c.float_ref_filter = Proc.new { | x | x.round } m = Currency::Money.new(1.99999999) m.should be_kind_of(Currency::Money) m.rep.should == 2000000 end end + + describe "the scale expression is configurable" do + before(:all) do + @config = Currency::Config.new + end + + before(:each) do + Currency::Config.current = nil + Currency::Config.send(:class_variable_set, "@@default", nil) + end + + it "should have a scale_exp setter" do + Currency::Config.current.should respond_to(:scale_exp=) + end + + it "has a 'scale' reader" do + Currency::Config.current.should respond_to(:scale) + end + + it "uses the scale reader from the config when creating new Money object" do + Currency::Config.should_receive(:current).and_return(@config) + @config.should_receive(:scale).and_return(100) + 10.money + end + + it "can be configured using a block" do + Currency::Config.configure do |config| + config.scale_exp = 6 + end -end # class - - + 10.money.currency.scale_exp.should == 6 + + Currency::Config.configure do |config| + config.scale_exp = 4 + end + 10.money.currency.scale_exp.should == 4 + end + + it "can be configured using straight setters" do + 10.money(:USD).currency.scale_exp.should == 2 + Currency::Config.current.scale_exp = 6 + 10.money(:USD).currency.scale_exp.should == 6 + end + end +end \ No newline at end of file diff --git a/spec/historical_writer_spec.rb b/spec/historical_writer_spec.rb index c061d30..d56cd85 100644 --- a/spec/historical_writer_spec.rb +++ b/spec/historical_writer_spec.rb @@ -1,121 +1,121 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require File.dirname(__FILE__) + '/ar_spec_helper' require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/historical' require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/historical/writer' require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/xe' require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/new_york_fed' include Currency RATE_CLASS = Exchange::Rate::Source::Historical::Rate TABLE_NAME = RATE_CLASS.table_name class HistoricalRateMigration < ActiveRecord::Migration def self.up RATE_CLASS.__create_table(self) end def self.down drop_table TABLE_NAME.to_sym end end describe "HistoricalWriter" do before(:all) do ActiveRecord::Base.establish_connection(database_spec) @currency_test_migration ||= HistoricalRateMigration schema_down schema_up @xe_src = Exchange::Rate::Source::Xe.new @fed_src = Exchange::Rate::Source::NewYorkFed.new end after(:all) do schema_down end def setup_writer(source) writer = Exchange::Rate::Source::Historical::Writer.new writer.time_quantitizer = :current writer.required_currencies = [ :USD, :GBP, :EUR, :CAD ] writer.base_currencies = [ :USD ] writer.preferred_currencies = writer.required_currencies writer.reciprocal_rates = true writer.all_rates = true writer.identity_rates = false writer.source = source writer end - it "does stuff with a Xe writer" do + it "can read, parse and write XE data" do writer = setup_writer(@xe_src) rates = writer.write_rates rates.size.should == 12 assert_h_rates(rates, writer) end - it "does stuff with NewYorkFed (will fail on weekends)" do + it "can read, parse and write NewYorkFed data (will fail on weekends)" do if @fed_src.available? writer = setup_writer(@fed_src) rates = writer.write_rates rates.size.should == 12 assert_h_rates(rates, writer) end end def assert_h_rates(rates, writer = nil) hr0 = rates[0] hr0.should_not be_nil rates.each do | hr | found_hr = nil begin found_hr = hr.find_matching_this(:first) found_hr.should_not be_nil rescue Object => err raise "#{hr.inspect}: #{err}:\n#{err.backtrace.inspect}" end assert_equal_rate(hr, found_hr) assert_rate_defaults(hr, writer) hr.instance_eval do date.should == hr0.date date_0.should == hr0.date_0 date_1.should == hr0.date_1 source.should == hr0.source end end end def assert_equal_rate(hr0, hr) tollerance = 0.00001 hr.c1.to_s.should == hr0.c1.to_s hr.c2.to_s.should == hr0.c2.to_s hr.source.should == hr0.source hr0.rate.should be_close(hr.rate, tollerance) hr0.rate_avg.should be_close(hr.rate_avg, tollerance) hr0.rate_samples.should == hr.rate_samples.should hr0.rate_lo.should be_close(hr.rate_lo, tollerance) hr0.rate_hi.should be_close(hr.rate_hi, tollerance) hr0.rate_date_0.should be_close(hr.rate_date_0, tollerance) hr0.rate_date_1.should be_close(hr.rate_date_1, tollerance) hr0.date.should == hr.date hr0.date_0.should == hr.date_0 hr0.date_1.should == hr.date_1 hr0.derived.should == hr.derived end def assert_rate_defaults(hr, writer) hr.source.should == writer.source.name hr.rate_avg.should == hr.rate hr.rate_samples.should == 1 hr.rate_lo.should == hr.rate hr.rate_hi.should == hr.rate hr.rate_date_0.should == hr.rate hr.rate_date_1.should == hr.rate end end \ No newline at end of file
acvwilson/currency
f6003d94524c855133eca9d3b7b6cb74614dabe4
CHANGED: FedralReserve specs use real feeds again CHANGED: HistoricalWriter specs
diff --git a/lib/currency.rb b/lib/currency.rb index 736fd54..8d98101 100644 --- a/lib/currency.rb +++ b/lib/currency.rb @@ -1,143 +1,143 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # # = Currency # # The Currency package provides an object-oriented model of: # # * currencies # * exchanges # * exchange rates # * exchange rate sources # * monetary values # # The core classes are: # # * Currency::Money - uses a scaled integer representation of a monetary value and performs accurate conversions to and from string values. # * Currency::Currency - provides an object-oriented representation of a currency. # * Currency::Exchange::Base - the base class for a currency exchange rate provider. # * Currency::Exchange::Rate::Source::Base - the base class for an on-demand currency exchange rate data provider. # * Currency::Exchange::Rate::Source::Provider - the base class for a bulk exchange rate data provider. # * Currency::Exchange::Rate - represents a exchange rate between two currencies. # # # The example below uses Currency::Exchange::Xe to automatically get # exchange rates from http://xe.com/ : # # require 'currency' # require 'currency/exchange/rate/deriver' # require 'currency/exchange/rate/source/xe' # require 'currency/exchange/rate/source/timed_cache' # # # Rate source initialization # provider = Currency::Exchange::Rate::Source::Xe.new # deriver = Currency::Exchange::Rate::Deriver.new(:source => provider) # cache = Currency::Exchange::Rate::Source::TimedCache.new(:source => deriver) # Currency::Exchange::Rate::Source.default = cache # # usd = Currency::Money('6.78', :USD) # puts "usd = #{usd.format}" # cad = usd.convert(:CAD) # puts "cad = #{cad.format}" # # == ActiveRecord Suppport # # This package also contains ActiveRecord support for money values: # # require 'currency' # require 'currency/active_record' # # class Entry < ActiveRecord::Base # money :amount # end # # In the example above, the entries.amount database column is an INTEGER that represents US cents. # The currency code of the money value can be stored in an additional database column or a default currency can be used. # # == Recent Enhancements # # === Storage and retrival of historical exchange rates # # * See Currency::Exchange::Rate::Source::Historical # * See Currency::Exchange::Rate::Source::Historical::Writer # # === Automatic derivation of rates from base rates. # # * See Currency::Exchange::Rate::Deriver # # === Rate caching # # * See Currency::Exchange::Rate::Source::TimedCache # # === Rate Providers # # * See Currency::Exchange::Rate::Source::Xe # * See Currency::Exchange::Rate::Source::NewYorkFed # * See Currency::Exchange::Rate::Source::TheFinancials # # === Customizable formatting and parsing # # * See Currency::Formatter # * See Currency::Parser # # == Future Enhancements # # * Support for inflationary rates within a currency, e.g. $10 USD in the year 1955 converted to 2006 USD. # # == SVN Repo # # svn checkout svn://rubyforge.org/var/svn/currency/currency/trunk # # == Examples # # See the examples/ and test/ directorys # # == Author # # Kurt Stephens http://kurtstephens.com # # == Support # # http://rubyforge.org/forum/forum.php?forum_id=7643 # # == Copyright # # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # module Currency # Use this function instead of Money#new: # # Currency::Money("12.34", :CAD) # # Do not do this: # # Currency::Money.new("12.34", :CAD) # # See Money#new. def self.Money(*opts) Money.new(*opts) end end $:.unshift(File.expand_path(File.dirname(__FILE__))) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'currency/currency_version' require 'currency/config' require 'currency/exception' require 'currency/money' require 'currency/currency' require 'currency/currency/factory' require 'currency/money' require 'currency/parser' require 'currency/formatter' # require this one before the parser and enjoy the weird bugs! require 'currency/exchange' require 'currency/exchange/rate' require 'currency/exchange/rate/deriver' require 'currency/exchange/rate/source' require 'currency/exchange/rate/source/test' require 'currency/exchange/time_quantitizer' require 'currency/core_extensions' -require 'active_support' +require 'active_support' # high(-er) precision rounding diff --git a/spec/federal_reserve_spec.rb b/spec/federal_reserve_spec.rb index 854b7ae..019337b 100644 --- a/spec/federal_reserve_spec.rb +++ b/spec/federal_reserve_spec.rb @@ -1,138 +1,71 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require File.dirname(__FILE__) + '/spec_helper' require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/federal_reserve' # Uncomment to avoid hitting the FED for every testrun -# Currency::Exchange::Rate::Source::FederalReserve.class_eval do -# def get_page_content -# %Q{ -# -# SPOT EXCHANGE RATE - DISNEYLAND -# -# ------------------------------ -# 14-Nov-08 1.1 -# } -# end -# end +Currency::Exchange::Rate::Source::FederalReserve.class_eval do + def get_page_content + %Q{ + + SPOT EXCHANGE RATE - DISNEYLAND + + ------------------------------ + 14-Nov-08 1.1 + } + end +end include Currency describe "FederalReserve" do def available? unless @available @available = @source.available? STDERR.puts "Warning: FederalReserve unavailable on Saturday and Sunday, skipping tests." unless @available end @available end - # Force FederalReserve Exchange. + # Called by the before(:all) in spec_helper + # Overriding here to force FederalReserve Exchange. + # TODO: when refactoring the whole spec to test only specific FedralReserve Stuff, make sure this one goes away def get_rate_source(source = nil) @source ||= Exchange::Rate::Source::FederalReserve.new(:verbose => false) @deriver ||= Exchange::Rate::Deriver.new(:source => @source, :verbose => @source.verbose) end def get_rates @rates ||= @source.raw_rates end before(:all) do get_rate_source get_rates end before(:each) do get_rate_source end it "can retrieve rates from the FED" do @rates.should_not be_nil end it "can convert from USD to CAD" do usd = Money.new(123.45, :USD) cad = usd.convert(:CAD) - # cad.should_not be_nil - # cad.to_f.should be_kind_of(Numeric) + cad.should_not be_nil + cad.to_f.should be_kind_of(Numeric) end - it "can convert CAD to EUR" do + it "can do conversions from AUD to USD to JPY" do aud = Money.new(123.45, :AUD) usd = aud.convert(:USD) jpy = usd.convert(:JPY) - - # eur = cad.convert(:EUR) - # eur.should_not be_nil - # eur.to_f.should be_kind_of(Numeric) - # eur.rep.should > 0 + jpy.should_not be_nil + jpy.to_f.should be_kind_of(Numeric) end -end - -# class FederalReserveTest < TestBase -# before do -# super -# end -# -# -# @@available = nil -# -# # New York Fed rates are not available on Saturday and Sunday. -# def available? -# if @@available == nil -# @@available = @source.available? -# STDERR.puts "Warning: FederalReserve unavailable on Saturday and Sunday, skipping tests." unless @@available -# end -# @@available -# end -# -# -# def get_rate_source -# # Force FederalReserve Exchange. -# verbose = false -# source = @source = Exchange::Rate::Source::FederalReserve.new(:verbose => verbose) -# deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) -# end -# -# -# -# it "usd cad" do -# return unless available? -# -# # yesterday = Time.now.to_date - 1 -# -# rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil -# #assert_not_nil rates[:USD] -# #assert_not_nil usd_cad = rates[:USD][:CAD] -# -# usd = Money.new(123.45, :USD).should_not == nil -# cad = usd.convert(:CAD).should_not == nil -# -# # assert_kind_of Numeric, m = (cad.to_f / usd.to_f) -# # $stderr.puts "m = #{m}" -# # assert_equal_float usd_cad, m, 0.001 -# end -# -# -# it "cad eur" do -# return unless available? -# -# rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil -# #assert_not_nil rates[:USD] -# #assert_not_nil usd_cad = rates[:USD][:CAD] -# #assert_not_nil usd_eur = rates[:USD][:EUR] -# -# cad = Money.new(123.45, :CAD).should_not == nil -# eur = cad.convert(:EUR).should_not == nil -# -# #assert_kind_of Numeric, m = (eur.to_f / cad.to_f) -# # $stderr.puts "m = #{m}" -# #assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 -# end -# -# end -# -# end # module -# +end \ No newline at end of file diff --git a/spec/historical_writer_spec.rb b/spec/historical_writer_spec.rb index b979547..c061d30 100644 --- a/spec/historical_writer_spec.rb +++ b/spec/historical_writer_spec.rb @@ -1,187 +1,121 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. +require File.dirname(__FILE__) + '/ar_spec_helper' -require 'test/ar_test_base' +require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/historical' +require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/historical/writer' +require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/xe' +require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/new_york_fed' -require 'rubygems' -require 'active_record' -require 'active_record/migration' +include Currency +RATE_CLASS = Exchange::Rate::Source::Historical::Rate +TABLE_NAME = RATE_CLASS.table_name -require 'currency' # For :type => :money - -require 'currency/exchange/rate/source/historical' -require 'currency/exchange/rate/source/historical/writer' -require 'currency/exchange/rate/source/xe' -require 'currency/exchange/rate/source/new_york_fed' - - -module Currency - -class HistoricalWriterTest < ArTestBase - - RATE_CLASS = Exchange::Rate::Source::Historical::Rate - TABLE_NAME = RATE_CLASS.table_name - - class HistoricalRateMigration < AR_M - def self.up - RATE_CLASS.__create_table(self) - end - - def self.down - drop_table TABLE_NAME.intern - end +class HistoricalRateMigration < ActiveRecord::Migration + def self.up + RATE_CLASS.__create_table(self) end - - def initialize(*args) - @currency_test_migration = HistoricalRateMigration - super - - @src = Exchange::Rate::Source::Xe.new - @src2 = Exchange::Rate::Source::NewYorkFed.new + def self.down + drop_table TABLE_NAME.to_sym end +end - - before do - super - +describe "HistoricalWriter" do + before(:all) do + ActiveRecord::Base.establish_connection(database_spec) + @currency_test_migration ||= HistoricalRateMigration + schema_down + schema_up + @xe_src = Exchange::Rate::Source::Xe.new + @fed_src = Exchange::Rate::Source::NewYorkFed.new end - - it "writer" do - src = @src.should_not == nil - writer = Exchange::Rate::Source::Historical::Writer.new().should_not == nil + after(:all) do + schema_down + end + + def setup_writer(source) + writer = Exchange::Rate::Source::Historical::Writer.new writer.time_quantitizer = :current writer.required_currencies = [ :USD, :GBP, :EUR, :CAD ] writer.base_currencies = [ :USD ] writer.preferred_currencies = writer.required_currencies writer.reciprocal_rates = true writer.all_rates = true writer.identity_rates = false - + writer.source = source writer end - - def writer_src - writer = test_writer - writer.source = @src - rates = writer.write_rates - rates.should_not == nil - rates.size.should > 0 - 12, rates.size.should_not == nil - assert_h_rates(rates, writer) - end - - - def writer_src2 - writer = test_writer - writer.source = @src2 - return unless writer.source.available? + it "does stuff with a Xe writer" do + writer = setup_writer(@xe_src) rates = writer.write_rates - rates.should_not == nil - rates.size.should > 0 rates.size.should == 12 assert_h_rates(rates, writer) end - - - def xxx_test_required_failure - writer = Exchange::Rate::Source::Historical::Writer.new().should_not == nil - src = @src.should_not == nil - writer.source = src - writer.required_currencies = [ :USD, :GBP, :EUR, :CAD, :ZZZ ] - writer.preferred_currencies = writer.required_currencies - assert_raises(::RuntimeError) { writer.selected_rates } - end - - - it "historical rates" do - # Make sure there are historical Rates avail for today. - writer_src - writer_src2 - - # Force Historical Rate Source. - source = Exchange::Rate::Source::Historical.new - deriver = Exchange::Rate::Deriver.new(:source => source) - Exchange::Rate::Source.default = deriver - - rates = source.get_raw_rates.should_not == nil - rates.empty?.should_not == true - # $stderr.puts "historical rates = #{rates.inspect}" - - rates = source.get_rates.should_not == nil - rates.empty?.should_not == true - # $stderr.puts "historical rates = #{rates.inspect}" - - m_usd = ::Currency.Money('1234.56', :USD, :now).should_not == nil - # $stderr.puts "m_usd = #{m_usd.to_s(:code => true)}" - m_eur = m_usd.convert(:EUR).should_not == nil - # $stderr.puts "m_eur = #{m_eur.to_s(:code => true)}" - + + it "does stuff with NewYorkFed (will fail on weekends)" do + if @fed_src.available? + writer = setup_writer(@fed_src) + rates = writer.write_rates + rates.size.should == 12 + assert_h_rates(rates, writer) + end end - - + def assert_h_rates(rates, writer = nil) - hr0 = rates[0].should_not == nil + hr0 = rates[0] + hr0.should_not be_nil rates.each do | hr | found_hr = nil begin - found_hr = hr.find_matching_this(:first).should_not == nil + found_hr = hr.find_matching_this(:first) + found_hr.should_not be_nil rescue Object => err raise "#{hr.inspect}: #{err}:\n#{err.backtrace.inspect}" end - - hr0.should_not == nil - - hr.date.should == hr0.date - hr.date_0.should == hr0.date_0 - hr.date_1.should == hr0.date_1 - hr.source.should == hr0.source - assert_equal_rate(hr, found_hr) assert_rate_defaults(hr, writer) + + hr.instance_eval do + date.should == hr0.date + date_0.should == hr0.date_0 + date_1.should == hr0.date_1 + source.should == hr0.source + end end end - def assert_equal_rate(hr0, hr) + tollerance = 0.00001 hr.c1.to_s.should == hr0.c1.to_s hr.c2.to_s.should == hr0.c2.to_s hr.source.should == hr0.source - assert_equal_float hr0.rate, hr.rate - assert_equal_float hr0.rate_avg, hr.rate_avg - hr.rate_samples.should == hr0.rate_samples - assert_equal_float hr0.rate_lo, hr.rate_lo - assert_equal_float hr0.rate_hi, hr.rate_hi - assert_equal_float hr0.rate_date_0, hr.rate_date_0 - assert_equal_float hr0.rate_date_1, hr.rate_date_1 - hr.date.should == hr0.date - hr.date_0.should == hr0.date_0 - hr.date_1.should == hr0.date_1 - hr.derived.should == hr0.derived + + hr0.rate.should be_close(hr.rate, tollerance) + hr0.rate_avg.should be_close(hr.rate_avg, tollerance) + hr0.rate_samples.should == hr.rate_samples.should + + hr0.rate_lo.should be_close(hr.rate_lo, tollerance) + hr0.rate_hi.should be_close(hr.rate_hi, tollerance) + hr0.rate_date_0.should be_close(hr.rate_date_0, tollerance) + hr0.rate_date_1.should be_close(hr.rate_date_1, tollerance) + + hr0.date.should == hr.date + hr0.date_0.should == hr.date_0 + hr0.date_1.should == hr.date_1 + hr0.derived.should == hr.derived end - def assert_rate_defaults(hr, writer) - hr.source if writer.should == writer.source.name - hr.rate_avg.should == hr.rate - 1.should == hr.rate_samples - hr.rate_lo.should == hr.rate - hr.rate_hi.should == hr.rate - hr.rate_date_0.should == hr.rate - hr.rate_date_1.should == hr.rate + hr.source.should == writer.source.name + hr.rate_avg.should == hr.rate + hr.rate_samples.should == 1 + hr.rate_lo.should == hr.rate + hr.rate_hi.should == hr.rate + hr.rate_date_0.should == hr.rate + hr.rate_date_1.should == hr.rate end - - def assert_equal_float(x1, x2, eps = 0.00001) - eps = (x1 * eps).abs - assert((x1 - eps) <= x2) - assert((x1 + eps) >= x2) - end - - -end - -end # module - +end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 92b8b50..addd97a 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,27 +1,25 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'spec' require File.dirname(__FILE__) + '/../lib/currency' require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/test' def setup(source = nil) - puts "setting source to: #{source.inspect}" rate_source ||= get_rate_source(source) Currency::Exchange::Rate::Source.default = rate_source # Force non-historical money values. Currency::Money.default_time = nil end def get_rate_source(source = nil) - puts "get_rate_source in spec_helper" source ||= Currency::Exchange::Rate::Source::Test.instance Currency::Exchange::Rate::Deriver.new(:source => source) end Spec::Runner.configure do |config| config.before(:all) {setup} end
acvwilson/currency
181724513b489b5e8bdd64ca2ef8df5c0fdaaa80
CHANGED: Fixed broken __subclass_responsibility exception CHANGED: raising on unavailable exchange rate (will comment out when gem is more stable) CHANGED: uncrazyfied Currency::Exchange::Rate::Source::Provider#get_uri CHANGED: simplified Currency::Exchange::Rate::Source::Provider#get_page_content CHANGED: misc changes to convert test unit to specs
diff --git a/lib/currency/exchange/rate/source/base.rb b/lib/currency/exchange/rate/source/base.rb index 9472981..bf77215 100644 --- a/lib/currency/exchange/rate/source/base.rb +++ b/lib/currency/exchange/rate/source/base.rb @@ -1,166 +1,166 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'currency/exchange/rate/source' # = Currency::Exchange::Rate::Source::Base # # The Currency::Exchange::Rate::Source::Base class is the base class for # currency exchange rate providers. # # Currency::Exchange::Rate::Source::Base subclasses are Currency::Exchange::Rate # factories. # # Represents a method of converting between two currencies. # # See Currency;:Exchange::Rate::source for more details. # class Currency::Exchange::Rate::Source::Base # The name of this Exchange. attr_accessor :name # Currency to use as pivot for deriving rate pairs. # Defaults to :USD. attr_accessor :pivot_currency # If true, this Exchange will log information. attr_accessor :verbose attr_accessor :time_quantitizer def initialize(opt = { }) @name = nil @verbose = nil unless defined? @verbose @pivot_currency ||= :USD @rate = { } @currencies = nil opt.each_pair{|k,v| self.send("#{k}=", v)} end - def __subclass_responsibility(meth) + def __subclass_responsibility(method) raise ::Currency::Exception::SubclassResponsibility, [ "#{self.class}#\#{meth}", :class, self.class, :method, method, ] end # Converts Money m in Currency c1 to a new # Money value in Currency c2. def convert(m, c2, time = nil, c1 = nil) c1 = m.currency if c1 == nil time = m.time if time == nil time = normalize_time(time) if c1 == c2 && normalize_time(m.time) == time m else rate = rate(c1, c2, time) - # raise ::Currency::Exception::UnknownRate, "#{c1} #{c2} #{time}" unless rate + raise ::Currency::Exception::UnknownRate, "Cannot convert #{m} from #{c1} to #{c2} at time #{time}" unless rate rate && ::Currency::Money(rate.convert(m, c1), c2, time) end end # Flush all cached Rate. def clear_rates @rate.clear @currencies = nil end # Flush any cached Rate between Currency c1 and c2. def clear_rate(c1, c2, time, recip = true) time = time && normalize_time(time) @rate["#{c1}:#{c2}:#{time}"] = nil @rate["#{c2}:#{c1}:#{time}"] = nil if recip time end # Returns the cached Rate between Currency c1 and c2 at a given time. # # Time is normalized using #normalize_time(time) # # Subclasses can override this method to implement # rate expiration rules. # def rate(c1, c2, time) time = time && normalize_time(time) @rate["#{c1}:#{c2}:#{time}"] ||= get_rate(c1, c2, time) end # Gets all rates available by this source. # def rates(time = nil) __subclass_responsibility(:rates) end # Returns a list of Currencies that the rate source provides. # # Subclasses can override this method. def currencies @currencies ||= rates.collect{| r | [ r.c1, r.c2 ]}.flatten.uniq end # Determines and creates the Rate between Currency c1 and c2. # # May attempt to use a pivot currency to bridge between # rates. # def get_rate(c1, c2, time) __subclass_responsibility(:get_rate) end # Returns a base Rate. # # Subclasses are required to implement this method. def get_rate_base(c1, c2, time) __subclass_responsibility(:get_rate_base) end # Returns a list of all available rates. # # Subclasses must override this method. def get_rates(time = nil) __subclass_responsibility(:get_rates) end # Called by implementors to construct new Rate objects. def new_rate(c1, c2, c1_to_c2_rate, time = nil, derived = nil) c1 = ::Currency::Currency.get(c1) c2 = ::Currency::Currency.get(c2) rate = ::Currency::Exchange::Rate.new(c1, c2, c1_to_c2_rate, name, time, derived) # $stderr.puts "new_rate = #{rate}" rate end # Normalizes rate time to a quantitized value. # # Subclasses can override this method. def normalize_time(time) time && (time_quantitizer || ::Currency::Exchange::TimeQuantitizer.current).quantitize_time(time) end # Returns a simple string rep. def to_s "#<#{self.class.name} #{self.name && self.name.inspect}>" end alias :inspect :to_s end # class diff --git a/lib/currency/exchange/rate/source/federal_reserve.rb b/lib/currency/exchange/rate/source/federal_reserve.rb index 3696dab..98ba5d5 100644 --- a/lib/currency/exchange/rate/source/federal_reserve.rb +++ b/lib/currency/exchange/rate/source/federal_reserve.rb @@ -1,160 +1,151 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. -require 'currency/exchange/rate/source/provider' +require File.dirname(__FILE__) + '/provider' require 'net/http' require 'open-uri' - # Connects to http://www.federalreserve.gov/releases/H10/hist/dat00_<country>.txtb # Parses all known currency files. # class Currency::Exchange::Rate::Source::FederalReserve < ::Currency::Exchange::Rate::Source::Provider # Defines the pivot currency for http://www.federalreserve.gov/releases/H10/hist/dat00_#{country_code}.txt data files. PIVOT_CURRENCY = :USD # Arbitrary currency code used by www.federalreserve.gov for # naming historical data files. # Used internally. attr_accessor :country_code def initialize(*opt) self.uri = 'http://www.federalreserve.gov/releases/H10/hist/dat00_#{country_code}.txt' self.country_code = '' @raw_rates = nil super(*opt) end - # Returns 'federalreserve.gov'. def name 'federalreserve.gov' end - # FIXME? #def available?(time = nil) # time ||= Time.now # ! [0, 6].include?(time.wday) ? true : false #end def clear_rates @raw_rates = nil super end - def raw_rates rates @raw_rates end # Maps bizzare federalreserve.gov country codes to ISO currency codes. # May only work for the dat00_XX.txt data files. # See http://www.jhall.demon.co.uk/currency/by_country.html # # Some data files list reciprocal rates! - @@country_to_currency = - { + @@country_to_currency = { 'al' => [ :AUD, :USD ], # 'au' => :ASH, # AUSTRIAN SHILLING: pre-EUR? 'bz' => [ :USD, :BRL ], 'ca' => [ :USD, :CAD ], 'ch' => [ :USD, :CNY ], 'dn' => [ :USD, :DKK ], 'eu' => [ :EUR, :USD ], # 'gr' => :XXX, # Greece Drachma: pre-EUR? 'hk' => [ :USD, :HKD ], 'in' => [ :USD, :INR ], 'ja' => [ :USD, :JPY ], 'ma' => [ :USD, :MYR ], 'mx' => [ :USD, :MXN ], # OR MXP? 'nz' => [ :NZD, :USD ], 'no' => [ :USD, :NOK ], 'ko' => [ :USD, :KRW ], 'sf' => [ :USD, :ZAR ], 'sl' => [ :USD, :LKR ], 'sd' => [ :USD, :SEK ], 'sz' => [ :USD, :CHF ], 'ta' => [ :USD, :TWD ], # New Taiwan Dollar. 'th' => [ :USD, :THB ], 'uk' => [ :GBP, :USD ], 've' => [ :USD, :VEB ], } - # Parses text file for rates. def parse_rates(data = nil) data = get_page_content unless data rates = [ ] @raw_rates ||= { } $stderr.puts "#{self}: parse_rates: data =\n#{data}" if @verbose # Rates are USD/currency so # c1 = currency # c2 = :USD c1, c2 = @@country_to_currency[country_code] unless c1 && c2 raise ::Currency::Exception::UnavailableRates, "Cannot determine currency code for federalreserve.gov country code #{country_code.inspect}" end data.split(/\r?\n\r?/).each do | line | # day month yy rate m = /^\s*(\d\d?)-([A-Z][a-z][a-z])-(\d\d)\s+([\d\.]+)/.match(line) next unless m day = m[1].to_i month = m[2] year = m[3].to_i if year >= 50 and year < 100 year += 1900 elsif year < 50 year += 2000 end date = Time.parse("#{day}-#{month}-#{year} 12:00:00 -05:00") # USA NY => EST rate = m[4].to_f - STDERR.puts "#{c1} #{c2} #{rate}\t#{date}" if @verbose + # STDERR.puts "#{c1} #{c2} #{rate}\t#{date}" if @verbose rates << new_rate(c1, c2, rate, date) ((@raw_rates[date] ||= { })[c1] ||= { })[c2] ||= rate ((@raw_rates[date] ||= { })[c2] ||= { })[c1] ||= 1.0 / rate end # Put most recent rate first. # See Provider#get_rate. rates.reverse! # $stderr.puts "rates = #{rates.inspect}" raise ::Currency::Exception::UnavailableRates, "No rates found in #{get_uri.inspect}" if rates.empty? rates end - # Return a list of known base rates. def load_rates(time = nil) # $stderr.puts "#{self}: load_rates(#{time})" if @verbose self.date = time rates = [ ] @@country_to_currency.keys.each do | cc | self.country_code = cc rates.push(*parse_rates) end rates end - - end # class diff --git a/lib/currency/exchange/rate/source/provider.rb b/lib/currency/exchange/rate/source/provider.rb index d626f12..67fd95c 100644 --- a/lib/currency/exchange/rate/source/provider.rb +++ b/lib/currency/exchange/rate/source/provider.rb @@ -1,120 +1,117 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. -require 'currency/exchange/rate/source' - +require File.dirname(__FILE__) + '/../source' # Base class for rate data providers. # Assumes that rate sources provide more than one rate per query. class Currency::Exchange::Rate::Source::Provider < Currency::Exchange::Rate::Source::Base # Error during parsing of rates. class ParserError < ::Currency::Exception::RateSourceError; end # The URI used to access the rate source. attr_accessor :uri # The URI path relative to uri used to access the rate source. attr_accessor :uri_path # The Time used to query the rate source. # Typically set by #load_rates. attr_accessor :date # The name is the same as its #uri. alias :name :uri def initialize(*args) super @rates = { } end # Returns the date to query for rates. # Defaults to yesterday. + # TODO: use ActiveSupport here? def date @date || (Time.now - 24 * 60 * 60) # yesterday. end # Returns year of query date. def date_YYYY '%04d' % date.year end # Return month of query date. def date_MM '%02d' % date.month end # Returns day of query date. def date_DD '%02d' % date.day end # Returns the URI string as evaluated with this object. def get_uri - uri = self.uri - uri = "\"#{uri}\"" - uri = instance_eval(uri) + uri = instance_eval("\"#{self.uri}\"") $stderr.puts "#{self}: uri = #{uri.inspect}" if @verbose uri end - # Returns the URI content. def get_page_content - data = open(get_uri) { |data| data.read } - - data + open(get_uri) { |data| data.read } end # Clear cached rates from this source. def clear_rates @rates.clear super end # Returns current base Rates or calls load_rates to load them from the source. def rates(time = nil) time = time && normalize_time(time) @rates["#{time}"] ||= load_rates(time) end # Returns an array of base Rates from the rate source. # # Subclasses must define this method. def load_rates(time = nil) raise Currency::Exception::SubclassResponsibility, :load_rates end # Return a matching base rate. def get_rate(c1, c2, time) + # puts "Getting rates for c1: #{c1} and c2: #{c2} at #{time}\n rates: #{rates.map{|r| "#{r.c1}->#{r.c2}"}.inspect}" rates.each do | rate | + # puts " >#{rate.c1} == #{c1} && #{rate.c2} == #{c2} #{rate.c1 == c1} && #{rate.c2.to_s == c2.to_s}< " return rate if rate.c1 == c1 && - rate.c2 == c2 && + rate.c2.to_s == c2.to_s && # FIXME: understand why this second param needs to be cast to String for specs to pass (! time || normalize_time(rate.date) == time) end nil end alias :get_rate_base :get_rate # Returns true if a rate provider is available. def available?(time = nil) true end end # class diff --git a/spec/ar_column_spec.rb b/spec/ar_column_spec.rb index 8a3faab..e26da14 100644 --- a/spec/ar_column_spec.rb +++ b/spec/ar_column_spec.rb @@ -1,57 +1,56 @@ require File.dirname(__FILE__) + '/ar_spec_helper' - ################################################## # Basic CurrenyTest AR::B class # # TODO: Move elsewhere, combine with other AR tests TABLE_NAME = 'currency_column_test' class CurrencyColumnTestMigration < AR_M def self.up create_table TABLE_NAME.intern do |t| t.column :name, :string t.column :amount, :integer # Money t.column :amount_currency, :string, :size => 3 # Money.currency.code end end def self.down drop_table TABLE_NAME.intern end end class CurrencyColumnTest < AR_B set_table_name TABLE_NAME attr_money :amount, :currency_column => true end ################################################## describe "ActiveRecord macros" do before(:all) do AR_B.establish_connection(database_spec) @currency_test_migration ||= CurrencyColumnTestMigration @currency_test ||= CurrencyColumnTest schema_down schema_up end after(:all) do schema_down end it "can store and retrieve money values from a DB and automagically transfomr them to Money" do insert_records usd = @currency_test.find(@usd.id) usd.should == @usd usd.object_id.should_not == @usd.object_id # not same object cad = @currency_test.find(@cad.id) cad.should == @cad cad.object_id.should_not == @cad.object_id # not same object end end diff --git a/spec/federal_reserve_spec.rb b/spec/federal_reserve_spec.rb index 2b0d809..854b7ae 100644 --- a/spec/federal_reserve_spec.rb +++ b/spec/federal_reserve_spec.rb @@ -1,75 +1,138 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. -require 'test/test_base' - -require 'currency' # For :type => :money -require 'currency/exchange/rate/source/federal_reserve' - -module Currency - -class FederalReserveTest < TestBase - before do - super - end - - - @@available = nil - - # New York Fed rates are not available on Saturday and Sunday. +require File.dirname(__FILE__) + '/spec_helper' +require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/federal_reserve' + +# Uncomment to avoid hitting the FED for every testrun +# Currency::Exchange::Rate::Source::FederalReserve.class_eval do +# def get_page_content +# %Q{ +# +# SPOT EXCHANGE RATE - DISNEYLAND +# +# ------------------------------ +# 14-Nov-08 1.1 +# } +# end +# end + +include Currency +describe "FederalReserve" do def available? - if @@available == nil - @@available = @source.available? - STDERR.puts "Warning: FederalReserve unavailable on Saturday and Sunday, skipping tests." unless @@available + unless @available + @available = @source.available? + STDERR.puts "Warning: FederalReserve unavailable on Saturday and Sunday, skipping tests." unless @available end - @@available + @available end - - - def get_rate_source - # Force FederalReserve Exchange. - verbose = false - source = @source = Exchange::Rate::Source::FederalReserve.new(:verbose => verbose) - deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) + + # Force FederalReserve Exchange. + def get_rate_source(source = nil) + @source ||= Exchange::Rate::Source::FederalReserve.new(:verbose => false) + @deriver ||= Exchange::Rate::Deriver.new(:source => @source, :verbose => @source.verbose) end - - - - it "usd cad" do - return unless available? - - # yesterday = Time.now.to_date - 1 - - rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil - #assert_not_nil rates[:USD] - #assert_not_nil usd_cad = rates[:USD][:CAD] - - usd = Money.new(123.45, :USD).should_not == nil - cad = usd.convert(:CAD).should_not == nil - - # assert_kind_of Numeric, m = (cad.to_f / usd.to_f) - # $stderr.puts "m = #{m}" - # assert_equal_float usd_cad, m, 0.001 + + def get_rates + @rates ||= @source.raw_rates + end + + before(:all) do + get_rate_source + get_rates + end + + before(:each) do + get_rate_source + end + + it "can retrieve rates from the FED" do + @rates.should_not be_nil end + it "can convert from USD to CAD" do + usd = Money.new(123.45, :USD) - it "cad eur" do - return unless available? - - rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil - #assert_not_nil rates[:USD] - #assert_not_nil usd_cad = rates[:USD][:CAD] - #assert_not_nil usd_eur = rates[:USD][:EUR] - - cad = Money.new(123.45, :CAD).should_not == nil - eur = cad.convert(:EUR).should_not == nil - - #assert_kind_of Numeric, m = (eur.to_f / cad.to_f) - # $stderr.puts "m = #{m}" - #assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 + cad = usd.convert(:CAD) + # cad.should_not be_nil + # cad.to_f.should be_kind_of(Numeric) end - + + it "can convert CAD to EUR" do + aud = Money.new(123.45, :AUD) + usd = aud.convert(:USD) + jpy = usd.convert(:JPY) + + # eur = cad.convert(:EUR) + # eur.should_not be_nil + # eur.to_f.should be_kind_of(Numeric) + # eur.rep.should > 0 + end + end -end # module - +# class FederalReserveTest < TestBase +# before do +# super +# end +# +# +# @@available = nil +# +# # New York Fed rates are not available on Saturday and Sunday. +# def available? +# if @@available == nil +# @@available = @source.available? +# STDERR.puts "Warning: FederalReserve unavailable on Saturday and Sunday, skipping tests." unless @@available +# end +# @@available +# end +# +# +# def get_rate_source +# # Force FederalReserve Exchange. +# verbose = false +# source = @source = Exchange::Rate::Source::FederalReserve.new(:verbose => verbose) +# deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) +# end +# +# +# +# it "usd cad" do +# return unless available? +# +# # yesterday = Time.now.to_date - 1 +# +# rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil +# #assert_not_nil rates[:USD] +# #assert_not_nil usd_cad = rates[:USD][:CAD] +# +# usd = Money.new(123.45, :USD).should_not == nil +# cad = usd.convert(:CAD).should_not == nil +# +# # assert_kind_of Numeric, m = (cad.to_f / usd.to_f) +# # $stderr.puts "m = #{m}" +# # assert_equal_float usd_cad, m, 0.001 +# end +# +# +# it "cad eur" do +# return unless available? +# +# rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil +# #assert_not_nil rates[:USD] +# #assert_not_nil usd_cad = rates[:USD][:CAD] +# #assert_not_nil usd_eur = rates[:USD][:EUR] +# +# cad = Money.new(123.45, :CAD).should_not == nil +# eur = cad.convert(:EUR).should_not == nil +# +# #assert_kind_of Numeric, m = (eur.to_f / cad.to_f) +# # $stderr.puts "m = #{m}" +# #assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 +# end +# +# end +# +# end # module +# diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index c6b71ac..92b8b50 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,25 +1,27 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'spec' require File.dirname(__FILE__) + '/../lib/currency' require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/test' -def setup - rate_source ||= get_rate_source +def setup(source = nil) + puts "setting source to: #{source.inspect}" + rate_source ||= get_rate_source(source) Currency::Exchange::Rate::Source.default = rate_source # Force non-historical money values. Currency::Money.default_time = nil end -def get_rate_source - source = Currency::Exchange::Rate::Source::Test.instance +def get_rate_source(source = nil) + puts "get_rate_source in spec_helper" + source ||= Currency::Exchange::Rate::Source::Test.instance Currency::Exchange::Rate::Deriver.new(:source => source) end Spec::Runner.configure do |config| config.before(:all) {setup} end
acvwilson/currency
ce655a4e4d726a46a5b89775ece6b9ecf0b002ed
REMOVED: ArTestCore class/file CHANGED: added comments and cleanup
diff --git a/spec/ar_core_spec.rb b/spec/ar_core_spec.rb deleted file mode 100644 index 4286f10..0000000 --- a/spec/ar_core_spec.rb +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> -# See LICENSE.txt for details. - - -# ================================================================= -# = TODO: IS THIS STUFF ACTUALLY NEEDED? IF SO, MOVE TO AR HELPER = -# ================================================================= -require 'test/ar_test_base' - -module Currency - -class ArTestCore < ArTestBase - - ################################################## - # Basic CurrenyTest AR::B class - # - - TABLE_NAME = 'currency_test' - - class CurrencyTestMigration < AR_M - def self.up - create_table TABLE_NAME.intern do |t| - t.column :name, :string - t.column :amount, :integer # Money - end - end - - def self.down - drop_table TABLE_NAME.intern - end - end - - - class CurrencyTest < AR_B - set_table_name TABLE_NAME - attr_money :amount - end - - - ################################################## - - - before do - @currency_test_migration ||= CurrencyTestMigration - @currency_test ||= CurrencyTest - super - end - - - def teardown - super - # schema_down - end - - - ################################################## - # - # - - - it "insert" do - insert_records - end - -end - -end # module - diff --git a/spec/ar_spec_helper.rb b/spec/ar_spec_helper.rb index 12799dd..086adfd 100644 --- a/spec/ar_spec_helper.rb +++ b/spec/ar_spec_helper.rb @@ -1,125 +1,127 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # Copyright (C) 2008 Asa Wilson <acvwilson(at)gmail.com> # See LICENSE.txt for details. require File.dirname(__FILE__) + '/spec_helper' require 'active_record' require 'active_record/migration' require File.dirname(__FILE__) + '/../lib/currency/active_record' AR_M = ActiveRecord::Migration AR_B = ActiveRecord::Base def ar_setup AR_B.establish_connection(database_spec) # Subclasses can override this. @currency_test_migration ||= nil @currency_test ||= nil # schema_down schema_up end +# DB Connection info def database_spec # TODO: Get from ../config/database.yml:test # Create test database on: # MYSQL: # # sudo mysqladmin create test; # sudo mysql # grant all on test.* to test@localhost identified by 'test'; # flush privileges; # POSTGRES: # # CREATE USER test PASSWORD 'test'; # CREATE DATABASE test WITH OWNER = test; # # @database_spec = { # :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', # :host => ENV['TEST_DB_HOST'] || 'localhost', # :username => ENV['TEST_DB_USER'] || 'test', # :password => ENV['TEST_DB_PASS'] || 'test', # :database => ENV['TEST_DB_TEST'] || 'test' # } @database_spec = { :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', :host => ENV['TEST_DB_HOST'] || 'localhost', :username => ENV['TEST_DB_USER'] || 'root', :password => ENV['TEST_DB_PASS'] || '', :database => ENV['TEST_DB_TEST'] || 'currency_gem_test' } end +# Run AR migrations UP def schema_up return unless @currency_test_migration begin @currency_test_migration.migrate(:up) rescue Object =>e $stderr.puts "Warning: #{e}" end end + +# Run AR migrations DOWN def schema_down return unless @currency_test_migration begin @currency_test_migration.migrate(:down) rescue Object => e $stderr.puts "Warning: #{e}" end end -################################################## -# Scaffold -# - +# Scaffold: insert stuff into DB so we can test AR integration def insert_records delete_records @currency_test.reset_column_information @usd = @currency_test.new(:name => '#1: USD', :amount => Currency::Money.new("12.34", :USD)) @usd.save @cad = @currency_test.new(:name => '#2: CAD', :amount => Currency::Money.new("56.78", :CAD)) @cad.save end def delete_records @currency_test.destroy_all end ################################################## +# TODO: need this? def assert_equal_money(a,b) a.should_not be_nil b.should_not be_nil # Make sure a and b are not the same object. b.object_id.should_not == a.object_id b.id.should == a.id a.amount.should_not == nil a.amount.should be_kind_of(Currency::Money) b.amount.should_not == nil b.amount.should be_kind_of(Currency::Money) # Make sure that what gets stored in the database comes back out # when converted back to the original currency. b.amount.rep.should == a.amount.convert(b.amount.currency).rep end - +# TODO: need this? def assert_equal_currency(a,b) assert_equal_money a, b b.amount.rep.should == a.amount.rep b.amount.currency.should == a.amount.currency b.amount.currency.code.should == a.amount.currency.code end \ No newline at end of file
acvwilson/currency
6b6c143383eef3fe7e022dbfc4e38923a82a7819
VERSION BUMP
diff --git a/currency.gemspec b/currency.gemspec index 7260459..28c016c 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| s.name = %q{currency} - s.version = "0.5.1" + s.version = "0.5.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] s.date = %q{2008-11-14} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/currency_version.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_base_spec.rb", "spec/ar_column_spec.rb", "spec/ar_core_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} - s.summary = %q{currency 0.5.1} + s.summary = %q{currency 0.5.2} end \ No newline at end of file
acvwilson/currency
b6310fb6f3465d9cac12d7458dd966e1791ac3f7
CHANGED: search&replace for "should.not" "should_not"
diff --git a/spec/federal_reserve_spec.rb b/spec/federal_reserve_spec.rb index c7ec0e6..2b0d809 100644 --- a/spec/federal_reserve_spec.rb +++ b/spec/federal_reserve_spec.rb @@ -1,75 +1,75 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' # For :type => :money require 'currency/exchange/rate/source/federal_reserve' module Currency class FederalReserveTest < TestBase before do super end @@available = nil # New York Fed rates are not available on Saturday and Sunday. def available? if @@available == nil @@available = @source.available? STDERR.puts "Warning: FederalReserve unavailable on Saturday and Sunday, skipping tests." unless @@available end @@available end def get_rate_source # Force FederalReserve Exchange. verbose = false source = @source = Exchange::Rate::Source::FederalReserve.new(:verbose => verbose) deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) end it "usd cad" do return unless available? # yesterday = Time.now.to_date - 1 - rates = Exchange::Rate::Source.default.source.raw_rates.should.not == nil + rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil #assert_not_nil rates[:USD] #assert_not_nil usd_cad = rates[:USD][:CAD] - usd = Money.new(123.45, :USD).should.not == nil - cad = usd.convert(:CAD).should.not == nil + usd = Money.new(123.45, :USD).should_not == nil + cad = usd.convert(:CAD).should_not == nil # assert_kind_of Numeric, m = (cad.to_f / usd.to_f) # $stderr.puts "m = #{m}" # assert_equal_float usd_cad, m, 0.001 end it "cad eur" do return unless available? - rates = Exchange::Rate::Source.default.source.raw_rates.should.not == nil + rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil #assert_not_nil rates[:USD] #assert_not_nil usd_cad = rates[:USD][:CAD] #assert_not_nil usd_eur = rates[:USD][:EUR] - cad = Money.new(123.45, :CAD).should.not == nil - eur = cad.convert(:EUR).should.not == nil + cad = Money.new(123.45, :CAD).should_not == nil + eur = cad.convert(:EUR).should_not == nil #assert_kind_of Numeric, m = (eur.to_f / cad.to_f) # $stderr.puts "m = #{m}" #assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 end end end # module diff --git a/spec/historical_writer_spec.rb b/spec/historical_writer_spec.rb index 7d7d342..b979547 100644 --- a/spec/historical_writer_spec.rb +++ b/spec/historical_writer_spec.rb @@ -1,187 +1,187 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/ar_test_base' require 'rubygems' require 'active_record' require 'active_record/migration' require 'currency' # For :type => :money require 'currency/exchange/rate/source/historical' require 'currency/exchange/rate/source/historical/writer' require 'currency/exchange/rate/source/xe' require 'currency/exchange/rate/source/new_york_fed' module Currency class HistoricalWriterTest < ArTestBase RATE_CLASS = Exchange::Rate::Source::Historical::Rate TABLE_NAME = RATE_CLASS.table_name class HistoricalRateMigration < AR_M def self.up RATE_CLASS.__create_table(self) end def self.down drop_table TABLE_NAME.intern end end def initialize(*args) @currency_test_migration = HistoricalRateMigration super @src = Exchange::Rate::Source::Xe.new @src2 = Exchange::Rate::Source::NewYorkFed.new end before do super end it "writer" do - src = @src.should.not == nil - writer = Exchange::Rate::Source::Historical::Writer.new().should.not == nil + src = @src.should_not == nil + writer = Exchange::Rate::Source::Historical::Writer.new().should_not == nil writer.time_quantitizer = :current writer.required_currencies = [ :USD, :GBP, :EUR, :CAD ] writer.base_currencies = [ :USD ] writer.preferred_currencies = writer.required_currencies writer.reciprocal_rates = true writer.all_rates = true writer.identity_rates = false writer end def writer_src writer = test_writer writer.source = @src rates = writer.write_rates - rates.should.not == nil + rates.should_not == nil rates.size.should > 0 - 12, rates.size.should.not == nil + 12, rates.size.should_not == nil assert_h_rates(rates, writer) end def writer_src2 writer = test_writer writer.source = @src2 return unless writer.source.available? rates = writer.write_rates - rates.should.not == nil + rates.should_not == nil rates.size.should > 0 rates.size.should == 12 assert_h_rates(rates, writer) end def xxx_test_required_failure - writer = Exchange::Rate::Source::Historical::Writer.new().should.not == nil - src = @src.should.not == nil + writer = Exchange::Rate::Source::Historical::Writer.new().should_not == nil + src = @src.should_not == nil writer.source = src writer.required_currencies = [ :USD, :GBP, :EUR, :CAD, :ZZZ ] writer.preferred_currencies = writer.required_currencies assert_raises(::RuntimeError) { writer.selected_rates } end it "historical rates" do # Make sure there are historical Rates avail for today. writer_src writer_src2 # Force Historical Rate Source. source = Exchange::Rate::Source::Historical.new deriver = Exchange::Rate::Deriver.new(:source => source) Exchange::Rate::Source.default = deriver - rates = source.get_raw_rates.should.not == nil - rates.empty?.should.not == true + rates = source.get_raw_rates.should_not == nil + rates.empty?.should_not == true # $stderr.puts "historical rates = #{rates.inspect}" - rates = source.get_rates.should.not == nil - rates.empty?.should.not == true + rates = source.get_rates.should_not == nil + rates.empty?.should_not == true # $stderr.puts "historical rates = #{rates.inspect}" - m_usd = ::Currency.Money('1234.56', :USD, :now).should.not == nil + m_usd = ::Currency.Money('1234.56', :USD, :now).should_not == nil # $stderr.puts "m_usd = #{m_usd.to_s(:code => true)}" - m_eur = m_usd.convert(:EUR).should.not == nil + m_eur = m_usd.convert(:EUR).should_not == nil # $stderr.puts "m_eur = #{m_eur.to_s(:code => true)}" end def assert_h_rates(rates, writer = nil) - hr0 = rates[0].should.not == nil + hr0 = rates[0].should_not == nil rates.each do | hr | found_hr = nil begin - found_hr = hr.find_matching_this(:first).should.not == nil + found_hr = hr.find_matching_this(:first).should_not == nil rescue Object => err raise "#{hr.inspect}: #{err}:\n#{err.backtrace.inspect}" end - hr0.should.not == nil + hr0.should_not == nil hr.date.should == hr0.date hr.date_0.should == hr0.date_0 hr.date_1.should == hr0.date_1 hr.source.should == hr0.source assert_equal_rate(hr, found_hr) assert_rate_defaults(hr, writer) end end def assert_equal_rate(hr0, hr) hr.c1.to_s.should == hr0.c1.to_s hr.c2.to_s.should == hr0.c2.to_s hr.source.should == hr0.source assert_equal_float hr0.rate, hr.rate assert_equal_float hr0.rate_avg, hr.rate_avg hr.rate_samples.should == hr0.rate_samples assert_equal_float hr0.rate_lo, hr.rate_lo assert_equal_float hr0.rate_hi, hr.rate_hi assert_equal_float hr0.rate_date_0, hr.rate_date_0 assert_equal_float hr0.rate_date_1, hr.rate_date_1 hr.date.should == hr0.date hr.date_0.should == hr0.date_0 hr.date_1.should == hr0.date_1 hr.derived.should == hr0.derived end def assert_rate_defaults(hr, writer) hr.source if writer.should == writer.source.name hr.rate_avg.should == hr.rate 1.should == hr.rate_samples hr.rate_lo.should == hr.rate hr.rate_hi.should == hr.rate hr.rate_date_0.should == hr.rate hr.rate_date_1.should == hr.rate end def assert_equal_float(x1, x2, eps = 0.00001) eps = (x1 * eps).abs assert((x1 - eps) <= x2) assert((x1 + eps) >= x2) end end end # module diff --git a/spec/macro_spec.rb b/spec/macro_spec.rb index 029f92d..89a83e4 100644 --- a/spec/macro_spec.rb +++ b/spec/macro_spec.rb @@ -1,109 +1,109 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' require 'currency/macro' module Currency class MacroTest < TestBase class Record include ::Currency::Macro attr_accessor :date attr_accessor :gross attr_accessor :tax attr_accessor :net attr_accessor :currency attr_money :gross_money, :value => :gross, :time => :date, :currency => :currency attr_money :tax_money, :value => :tax, :time => :date, :currency => :currency attr_money :net_money, :value => :net, :time => :date, :currency => :currency def initialize self.date = Time.now self.currency = :USD end def compute_net self.net = self.gross - self.tax end def compute_net_money self.net_money = self.gross_money - self.tax_money end end before do super end ############################################ # Tests # it "read money" do assert_kind_of Record, r = Record.new - r.gross = 10.00.should.not == nil + r.gross = 10.00.should_not == nil r.gross.should == r.gross_money.to_f r.currency.should == r.gross_money.currency.code r.date.should == r.gross_money.time r end it "write money rep" do assert_kind_of Record, r = Record.new - r.gross_money = 10.00.should.not == nil + r.gross_money = 10.00.should_not == nil r.gross.should == r.gross_money.to_f r.currency.should == r.gross_money.currency.code r.date.should == r.gross_money.time r end it "money cache" do r = test_read_money - r_gross = r.gross.should.not == nil + r_gross = r.gross.should_not == nil r_gross.object_id.should == r.gross.object_id # Cache flush - r.gross = 12.00.should.not == nil + r.gross = 12.00.should_not == nil r.gross.should == r.gross_money.to_f - r_gross.object_id != r.gross.object_id.should.not == nil + r_gross.object_id != r.gross.object_id.should_not == nil end it "currency" do r = test_read_money - r.gross_money.currency.should.not == nil + r.gross_money.currency.should_not == nil r.currency.should == r.gross_money.currency.code end it "compute" do assert_kind_of Record, r = Record.new - r.gross = 10.00.should.not == nil - r.tax = 1.50.should.not == nil + r.gross = 10.00.should_not == nil + r.tax = 1.50.should_not == nil r.compute_net r.net.should == 8.50 r.net_money.to_f.should == r.net r.compute_net_money r.net.should == 8.50 r.net_money.to_f.should == r.net end end # class end # module diff --git a/spec/new_york_fed_spec.rb b/spec/new_york_fed_spec.rb index 7153167..fff9aff 100644 --- a/spec/new_york_fed_spec.rb +++ b/spec/new_york_fed_spec.rb @@ -1,73 +1,73 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' # For :type => :money require 'currency/exchange/rate/source/new_york_fed' module Currency class NewYorkFedTest < TestBase before do super end @@available = nil # New York Fed rates are not available on Saturday and Sunday. def available? if @@available == nil @@available = @source.available? STDERR.puts "Warning: NewYorkFed unavailable on Saturday and Sunday, skipping tests." end @@available end def get_rate_source # Force NewYorkFed Exchange. verbose = false source = @source = Exchange::Rate::Source::NewYorkFed.new(:verbose => verbose) deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) end it "usd cad" do return unless available? - rates = Exchange::Rate::Source.default.source.raw_rates.should.not == nil - rates[:USD].should.not == nil - usd_cad = rates[:USD][:CAD].should.not == nil + rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil + rates[:USD].should_not == nil + usd_cad = rates[:USD][:CAD].should_not == nil - usd = Money.new(123.45, :USD).should.not == nil - cad = usd.convert(:CAD).should.not == nil + usd = Money.new(123.45, :USD).should_not == nil + cad = usd.convert(:CAD).should_not == nil assert_kind_of Numeric, m = (cad.to_f / usd.to_f) # $stderr.puts "m = #{m}" assert_equal_float usd_cad, m, 0.001 end it "cad eur" do return unless available? - rates = Exchange::Rate::Source.default.source.raw_rates.should.not == nil - rates[:USD].should.not == nil - usd_cad = rates[:USD][:CAD].should.not == nil - usd_eur = rates[:USD][:EUR].should.not == nil + rates = Exchange::Rate::Source.default.source.raw_rates.should_not == nil + rates[:USD].should_not == nil + usd_cad = rates[:USD][:CAD].should_not == nil + usd_eur = rates[:USD][:EUR].should_not == nil - cad = Money.new(123.45, :CAD).should.not == nil - eur = cad.convert(:EUR).should.not == nil + cad = Money.new(123.45, :CAD).should_not == nil + eur = cad.convert(:EUR).should_not == nil assert_kind_of Numeric, m = (eur.to_f / cad.to_f) # $stderr.puts "m = #{m}" assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 end end end # module diff --git a/spec/parser_spec.rb b/spec/parser_spec.rb index f124def..f4fc32f 100644 --- a/spec/parser_spec.rb +++ b/spec/parser_spec.rb @@ -1,105 +1,105 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' module Currency class ParserTest < TestBase before do super @parser = ::Currency::Currency.USD.parser_or_default end ############################################ # Simple stuff. # it "default" do end it "thousands" do @parser.parse("1234567.89").rep.should == 123456789 assert_equal 123456789, @parser.parse("1,234,567.89").rep end it "cents" do @parser.parse("1234567.89").rep.should == 123456789 @parser.parse("1234567").rep.should == 123456700 @parser.parse("1234567.").rep.should == 123456700 @parser.parse("1234567.8").rep.should == 123456780 @parser.parse("1234567.891").rep.should == 123456789 @parser.parse("-1234567").rep.should == -123456700 @parser.parse("+1234567").rep.should == 123456700 end it "misc" do - m = "123.45 USD".money + "100 CAD".should.not == nil - (m.rep == 200.45).should.not == true + m = "123.45 USD".money + "100 CAD".should_not == nil + (m.rep == 200.45).should_not == true end it "round trip" do ::Currency::Currency.default = :USD - m = ::Currency::Money("1234567.89", :CAD).should.not == nil - m2 = ::Currency::Money(m.inspect).should.not == nil + m = ::Currency::Money("1234567.89", :CAD).should_not == nil + m2 = ::Currency::Money(m.inspect).should_not == nil m2.rep.should == m.rep m2.currency.should == m.currency m2.time.should == nil m2.inspect.should == m.inspect end it "round trip time" do ::Currency::Currency.default = :USD time = Time.now.getutc - m = ::Currency::Money("1234567.89", :CAD, time).should.not == nil - m.time.should.not == nil - m2 = ::Currency::Money(m.inspect).should.not == nil - m2.time.should.not == nil + m = ::Currency::Money("1234567.89", :CAD, time).should_not == nil + m.time.should_not == nil + m2 = ::Currency::Money(m.inspect).should_not == nil + m2.time.should_not == nil m2.rep.should == m.rep m2.currency.should == m.currency m2.time.to_i.should == m.time.to_i m2.inspect.should == m.inspect end it "time nil" do parser = ::Currency::Parser.new parser.time = nil - m = parser.parse("$1234.55").should.not == nil + m = parser.parse("$1234.55").should_not == nil m.time.should == nil end it "time" do parser = ::Currency::Parser.new parser.time = Time.new - m = parser.parse("$1234.55").should.not == nil + m = parser.parse("$1234.55").should_not == nil m.time.should == parser.time end it "time now" do parser = ::Currency::Parser.new parser.time = :now - m = parser.parse("$1234.55").should.not == nil - m1_time = m.time.should.not == nil + m = parser.parse("$1234.55").should_not == nil + m1_time = m.time.should_not == nil - m = parser.parse("$1234.55").should.not == nil - m2_time = m.time.should.not == nil + m = parser.parse("$1234.55").should_not == nil + m2_time = m.time.should_not == nil assert_not_equal m1_time, m2_time end end end # module diff --git a/spec/timed_cache_spec.rb b/spec/timed_cache_spec.rb index 93e98e9..0eadb87 100644 --- a/spec/timed_cache_spec.rb +++ b/spec/timed_cache_spec.rb @@ -1,95 +1,95 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' require 'currency/exchange/rate/source/xe' require 'currency/exchange/rate/source/timed_cache' module Currency class TimedCacheTest < TestBase before do super end def get_rate_source @source = source = Exchange::Rate::Source::Xe.new # source.verbose = true deriver = Exchange::Rate::Deriver.new(:source => source) @cache = cache = Exchange::Rate::Source::TimedCache.new(:source => deriver) cache end it "timed cache usd cad" do - rates = @source.raw_rates.should.not == nil - rates[:USD].should.not == nil - usd_cad = rates[:USD][:CAD].should.not == nil + rates = @source.raw_rates.should_not == nil + rates[:USD].should_not == nil + usd_cad = rates[:USD][:CAD].should_not == nil - usd = Money.new(123.45, :USD).should.not == nil - cad = usd.convert(:CAD).should.not == nil + usd = Money.new(123.45, :USD).should_not == nil + cad = usd.convert(:CAD).should_not == nil assert_kind_of Numeric, m = (cad.to_f / usd.to_f) # $stderr.puts "m = #{m}" assert_equal_float usd_cad, m, 0.001 end it "timed cache cad eur" do - rates = @source.raw_rates.should.not == nil - rates[:USD].should.not == nil - usd_cad = rates[:USD][:CAD].should.not == nil - usd_eur = rates[:USD][:EUR].should.not == nil + rates = @source.raw_rates.should_not == nil + rates[:USD].should_not == nil + usd_cad = rates[:USD][:CAD].should_not == nil + usd_eur = rates[:USD][:EUR].should_not == nil - cad = Money.new(123.45, :CAD).should.not == nil - eur = cad.convert(:EUR).should.not == nil + cad = Money.new(123.45, :CAD).should_not == nil + eur = cad.convert(:EUR).should_not == nil assert_kind_of Numeric, m = (eur.to_f / cad.to_f) # $stderr.puts "m = #{m}" assert_equal_float((1.0 / usd_cad) * usd_eur, m, 0.001) end it "reload" do # @cache.verbose = 5 test_timed_cache_cad_eur - rates = @source.raw_rates.should.not == nil - rates[:USD].should.not == nil - usd_cad_1 = rates[:USD][:CAD].should.not == nil + rates = @source.raw_rates.should_not == nil + rates[:USD].should_not == nil + usd_cad_1 = rates[:USD][:CAD].should_not == nil - t1 = @cache.rate_load_time.should.not == nil - t1_reload = @cache.rate_reload_time.should.not == nil + t1 = @cache.rate_load_time.should_not == nil + t1_reload = @cache.rate_reload_time.should_not == nil t1_reload.to_i.should > t1.to_i @cache.time_to_live = 5 @cache.time_to_live_fudge = 0 # puts @cache.rate_reload_time.to_i - @cache.rate_load_time.to_i - @cache.rate_reload_time.to_i - @cache.rate_load_time.to_i == @cache.time_to_live.should.not == nil + @cache.rate_reload_time.to_i - @cache.rate_load_time.to_i == @cache.time_to_live.should_not == nil sleep 10 test_timed_cache_cad_eur - t2 = @cache.rate_load_time.should.not == nil - t1.to_i != t2.to_i.should.not == nil + t2 = @cache.rate_load_time.should_not == nil + t1.to_i != t2.to_i.should_not == nil - rates = @source.raw_rates.should.not == nil - rates[:USD].should.not == nil - usd_cad_2 = rates[:USD][:CAD].should.not == nil + rates = @source.raw_rates.should_not == nil + rates[:USD].should_not == nil + usd_cad_2 = rates[:USD][:CAD].should_not == nil - usd_cad_1.object_id != usd_cad_2.object_id.should.not == nil + usd_cad_1.object_id != usd_cad_2.object_id.should_not == nil end end end # module
acvwilson/currency
4b5dde3a816efce2680f0e7742b24a95a510e16f
CHANGED: changed order of requires to make to_s stop misbehaving CHANGED: basic AR specs pass and AR setup is working
diff --git a/lib/currency.rb b/lib/currency.rb index 659a181..736fd54 100644 --- a/lib/currency.rb +++ b/lib/currency.rb @@ -1,143 +1,143 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # # = Currency # # The Currency package provides an object-oriented model of: # # * currencies # * exchanges # * exchange rates # * exchange rate sources # * monetary values # # The core classes are: # # * Currency::Money - uses a scaled integer representation of a monetary value and performs accurate conversions to and from string values. # * Currency::Currency - provides an object-oriented representation of a currency. # * Currency::Exchange::Base - the base class for a currency exchange rate provider. # * Currency::Exchange::Rate::Source::Base - the base class for an on-demand currency exchange rate data provider. # * Currency::Exchange::Rate::Source::Provider - the base class for a bulk exchange rate data provider. # * Currency::Exchange::Rate - represents a exchange rate between two currencies. # # # The example below uses Currency::Exchange::Xe to automatically get # exchange rates from http://xe.com/ : # # require 'currency' # require 'currency/exchange/rate/deriver' # require 'currency/exchange/rate/source/xe' # require 'currency/exchange/rate/source/timed_cache' # # # Rate source initialization # provider = Currency::Exchange::Rate::Source::Xe.new # deriver = Currency::Exchange::Rate::Deriver.new(:source => provider) # cache = Currency::Exchange::Rate::Source::TimedCache.new(:source => deriver) # Currency::Exchange::Rate::Source.default = cache # # usd = Currency::Money('6.78', :USD) # puts "usd = #{usd.format}" # cad = usd.convert(:CAD) # puts "cad = #{cad.format}" # # == ActiveRecord Suppport # # This package also contains ActiveRecord support for money values: # # require 'currency' # require 'currency/active_record' # # class Entry < ActiveRecord::Base # money :amount # end # # In the example above, the entries.amount database column is an INTEGER that represents US cents. # The currency code of the money value can be stored in an additional database column or a default currency can be used. # # == Recent Enhancements # # === Storage and retrival of historical exchange rates # # * See Currency::Exchange::Rate::Source::Historical # * See Currency::Exchange::Rate::Source::Historical::Writer # # === Automatic derivation of rates from base rates. # # * See Currency::Exchange::Rate::Deriver # # === Rate caching # # * See Currency::Exchange::Rate::Source::TimedCache # # === Rate Providers # # * See Currency::Exchange::Rate::Source::Xe # * See Currency::Exchange::Rate::Source::NewYorkFed # * See Currency::Exchange::Rate::Source::TheFinancials # # === Customizable formatting and parsing # # * See Currency::Formatter # * See Currency::Parser # # == Future Enhancements # # * Support for inflationary rates within a currency, e.g. $10 USD in the year 1955 converted to 2006 USD. # # == SVN Repo # # svn checkout svn://rubyforge.org/var/svn/currency/currency/trunk # # == Examples # # See the examples/ and test/ directorys # # == Author # # Kurt Stephens http://kurtstephens.com # # == Support # # http://rubyforge.org/forum/forum.php?forum_id=7643 # # == Copyright # # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # module Currency # Use this function instead of Money#new: # # Currency::Money("12.34", :CAD) # # Do not do this: # # Currency::Money.new("12.34", :CAD) # # See Money#new. def self.Money(*opts) Money.new(*opts) end end $:.unshift(File.expand_path(File.dirname(__FILE__))) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'currency/currency_version' require 'currency/config' require 'currency/exception' require 'currency/money' require 'currency/currency' require 'currency/currency/factory' require 'currency/money' -require 'currency/formatter' require 'currency/parser' +require 'currency/formatter' # require this one before the parser and enjoy the weird bugs! require 'currency/exchange' require 'currency/exchange/rate' require 'currency/exchange/rate/deriver' require 'currency/exchange/rate/source' require 'currency/exchange/rate/source/test' require 'currency/exchange/time_quantitizer' require 'currency/core_extensions' require 'active_support' diff --git a/spec/ar_column_spec.rb b/spec/ar_column_spec.rb index e8d5b66..8a3faab 100644 --- a/spec/ar_column_spec.rb +++ b/spec/ar_column_spec.rb @@ -1,76 +1,57 @@ -# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> -# See LICENSE.txt for details. - -# require 'test/ar_test_core' -# require 'currency' -# -# require 'rubygems' -# require 'active_record' -# require 'active_record/migration' -# require 'currency/active_record' - require File.dirname(__FILE__) + '/ar_spec_helper' -# module Currency -# -# class ArFieldTest < ArTestCore - ################################################## - # Basic CurrenyTest AR::B class - # +################################################## +# Basic CurrenyTest AR::B class +# - TABLE_NAME = 'currency_column_test' +# TODO: Move elsewhere, combine with other AR tests - class CurrencyColumnTestMigration < AR_M - def self.up - create_table TABLE_NAME.intern do |t| - t.column :name, :string - t.column :amount, :integer # Money - t.column :amount_currency, :string, :size => 3 # Money.currency.code - end - end +TABLE_NAME = 'currency_column_test' - def self.down - drop_table TABLE_NAME.intern +class CurrencyColumnTestMigration < AR_M + def self.up + create_table TABLE_NAME.intern do |t| + t.column :name, :string + t.column :amount, :integer # Money + t.column :amount_currency, :string, :size => 3 # Money.currency.code end end - class CurrencyColumnTest < AR_B - set_table_name TABLE_NAME - attr_money :amount, :currency_column => true - end - - ################################################## - + def self.down + drop_table TABLE_NAME.intern + end +end - # def teardown - # super - # end +class CurrencyColumnTest < AR_B + set_table_name TABLE_NAME + attr_money :amount, :currency_column => true +end - ################################################## +################################################## describe "ActiveRecord macros" do before(:all) do AR_B.establish_connection(database_spec) @currency_test_migration ||= CurrencyColumnTestMigration @currency_test ||= CurrencyColumnTest - # schema_down + schema_down schema_up end after(:all) do - # schema_down + schema_down end - it "field" do + it "can store and retrieve money values from a DB and automagically transfomr them to Money" do insert_records usd = @currency_test.find(@usd.id) - usd.should_not be_nil - assert_equal_currency usd, @usd + usd.should == @usd + usd.object_id.should_not == @usd.object_id # not same object cad = @currency_test.find(@cad.id) - cad.should_not be_nil - assert_equal_currency cad, @cad + cad.should == @cad + cad.object_id.should_not == @cad.object_id # not same object end end diff --git a/spec/ar_spec_helper.rb b/spec/ar_spec_helper.rb index 3a42558..12799dd 100644 --- a/spec/ar_spec_helper.rb +++ b/spec/ar_spec_helper.rb @@ -1,125 +1,125 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # Copyright (C) 2008 Asa Wilson <acvwilson(at)gmail.com> # See LICENSE.txt for details. require File.dirname(__FILE__) + '/spec_helper' require 'active_record' require 'active_record/migration' require File.dirname(__FILE__) + '/../lib/currency/active_record' AR_M = ActiveRecord::Migration AR_B = ActiveRecord::Base def ar_setup AR_B.establish_connection(database_spec) # Subclasses can override this. @currency_test_migration ||= nil @currency_test ||= nil # schema_down schema_up end def database_spec # TODO: Get from ../config/database.yml:test # Create test database on: # MYSQL: # # sudo mysqladmin create test; # sudo mysql # grant all on test.* to test@localhost identified by 'test'; # flush privileges; # POSTGRES: # # CREATE USER test PASSWORD 'test'; # CREATE DATABASE test WITH OWNER = test; # # @database_spec = { # :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', # :host => ENV['TEST_DB_HOST'] || 'localhost', # :username => ENV['TEST_DB_USER'] || 'test', # :password => ENV['TEST_DB_PASS'] || 'test', # :database => ENV['TEST_DB_TEST'] || 'test' # } @database_spec = { :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', :host => ENV['TEST_DB_HOST'] || 'localhost', :username => ENV['TEST_DB_USER'] || 'root', :password => ENV['TEST_DB_PASS'] || '', :database => ENV['TEST_DB_TEST'] || 'currency_gem_test' } end def schema_up return unless @currency_test_migration begin @currency_test_migration.migrate(:up) rescue Object =>e $stderr.puts "Warning: #{e}" end end def schema_down return unless @currency_test_migration begin @currency_test_migration.migrate(:down) rescue Object => e $stderr.puts "Warning: #{e}" end end ################################################## # Scaffold # def insert_records delete_records @currency_test.reset_column_information @usd = @currency_test.new(:name => '#1: USD', :amount => Currency::Money.new("12.34", :USD)) @usd.save @cad = @currency_test.new(:name => '#2: CAD', :amount => Currency::Money.new("56.78", :CAD)) @cad.save end def delete_records @currency_test.destroy_all end ################################################## def assert_equal_money(a,b) a.should_not be_nil b.should_not be_nil # Make sure a and b are not the same object. b.object_id.should_not == a.object_id b.id.should == a.id - a.amount.should.not == nil - a.amount.should be_kind_of(Money) - b.amount.should.not == nil - b.amount.should be_kind_of(Money) + a.amount.should_not == nil + a.amount.should be_kind_of(Currency::Money) + b.amount.should_not == nil + b.amount.should be_kind_of(Currency::Money) # Make sure that what gets stored in the database comes back out # when converted back to the original currency. b.amount.rep.should == a.amount.convert(b.amount.currency).rep end def assert_equal_currency(a,b) assert_equal_money a, b b.amount.rep.should == a.amount.rep b.amount.currency.should == a.amount.currency b.amount.currency.code.should == a.amount.currency.code end \ No newline at end of file diff --git a/spec/money_spec.rb b/spec/money_spec.rb index e1d0469..73d0fd1 100644 --- a/spec/money_spec.rb +++ b/spec/money_spec.rb @@ -1,355 +1,347 @@ require File.dirname(__FILE__) + '/spec_helper' - +# require File.dirname(__FILE__) + '/../lib/currency/formatter' describe Currency::Money do it "create" do m = Currency::Money.new(1.99) m.should be_kind_of(Currency::Money) Currency::Currency.default.should == m.currency :USD.should == m.currency.code end describe "object money method" do it "works with a float" do m = 1.99.money(:USD) m.should be_kind_of(Currency::Money) :USD.should == m.currency.code m.rep.should == 1990000 end it "works with a FixNum" do m = 199.money(:CAD) m.should be_kind_of(Currency::Money) :CAD.should == m.currency.code m.rep.should == 199000000 end it "works with a string" do m = "13.98".money(:CAD) m.should be_kind_of(Currency::Money) :CAD.should == m.currency.code m.rep.should == 13980000 end it "works with a string again" do m = "45.99".money(:EUR) m.should be_kind_of(Currency::Money) :EUR.should == m.currency.code m.rep.should == 45990000 end - - it "creates money objects from strings" do - "12.0001".money(:USD).to_s.should == "$12.0001" - # "12.000108".money(:USD).to_s(:thousands => false, :decimals => 5).should == "$12.00011" - @money = Currency::Money.new_rep(1234567890000, :USD, nil) - - Currency::Money.new("12.000108").to_s(:thousands => false, :decimals => 5).should == "$12.00011" - end end def zero_money @zero_money ||= Currency::Money.new(0) end it "zero" do zero_money.negative?.should_not == true zero_money.zero?.should_not == nil zero_money.positive?.should_not == true end def negative_money @negative_money ||= Currency::Money.new(-1.00, :USD) end it "negative" do negative_money.negative?.should_not == nil negative_money.zero?.should_not == true negative_money.positive?.should_not == true end def positive_money @positive_money ||= Currency::Money.new(2.99, :USD) end it "positive" do positive_money.negative?.should_not == true positive_money.zero?.should_not == true positive_money.positive?.should_not == nil end it "relational" do n = negative_money z = zero_money p = positive_money (n.should < p) (n > p).should_not == true (p < n).should_not == true (p.should > n) (p != n).should_not == nil (z.should <= z) (z.should >= z) (z.should <= p) (n.should <= z) (z.should >= n) n.should == n p.should == p z.should == zero_money end it "compare" do n = negative_money z = zero_money p = positive_money (n <=> p).should == -1 (p <=> n).should == 1 (p <=> z).should == 1 (n <=> n).should == 0 (z <=> z).should == 0 (p <=> p).should == 0 end it "rep" do m = Currency::Money.new(123, :USD) m.should_not == nil m.rep.should == 123000000 m = Currency::Money.new(123.45, :USD) m.should_not == nil m.rep.should == 123450000 m = Currency::Money.new("123.456", :USD) m.should_not == nil m.rep.should == 123456000 end it "convert" do m = Currency::Money.new("123.456", :USD) m.should_not == nil m.rep.should == 123456000 m.to_i.should == 123 m.to_f.should == 123.456 m.to_s.should == "$123.456000" end it "eql" do usd1 = Currency::Money.new(123, :USD) usd1.should_not == nil usd2 = Currency::Money.new("123", :USD) usd2.should_not == nil usd1.currency.code.should == :USD usd2.currency.code.should == :USD usd2.rep.should == usd1.rep usd1.should == usd2 end it "not eql" do usd1 = Currency::Money.new(123, :USD) usd1.should_not == nil usd2 = Currency::Money.new("123.01", :USD) usd2.should_not == nil usd1.currency.code.should == :USD usd2.currency.code.should == :USD usd2.rep.should_not == usd1.rep (usd1 != usd2).should_not == nil ################ # currency != # rep == usd = Currency::Money.new(123, :USD) usd.should_not == nil cad = Currency::Money.new(123, :CAD) cad.should_not == nil usd.currency.code.should == :USD cad.currency.code.should == :CAD cad.rep.should == usd.rep (usd.currency != cad.currency).should_not == nil (usd != cad).should_not == nil end describe "operations" do before(:each) do @usd = Currency::Money.new(123.45, :USD) @cad = Currency::Money.new(123.45, :CAD) end it "should work" do @usd.should_not == nil @cad.should_not == nil end it "handle negative money" do # - Currency::Money => Currency::Money (- @usd).rep.should == -123450000 (- @usd).currency.code.should == :USD (- @cad).rep.should == -123450000 (- @cad).currency.code.should == :CAD end it "should add monies of the same currency" do m = (@usd + @usd) m.should be_kind_of(Currency::Money) m.rep.should == 246900000 m.currency.code.should == :USD end it "should add monies of different currencies and return USD" do m = (@usd + @cad) m.should be_kind_of(Currency::Money) m.rep.should == 228890724 m.currency.code.should == :USD end it "should add monies of different currencies and return CAD" do m = (@cad + @usd) m.should be_kind_of(Currency::Money) m.rep.should == 267985260 m.currency.code.should == :CAD end it "should subtract monies of the same currency" do m = (@usd - @usd) m.should be_kind_of(Currency::Money) m.rep.should == 0 m.currency.code.should == :USD end it "should subtract monies of different currencies and return USD" do m = (@usd - @cad) m.should be_kind_of(Currency::Money) m.rep.should == 18009276 m.currency.code.should == :USD end it "should subtract monies of different currencies and return CAD" do m = (@cad - @usd) m.should be_kind_of(Currency::Money) m.rep.should == -21085260 m.currency.code.should == :CAD end it "should multiply by numerics and return money" do m = (@usd * 0.5) m.should be_kind_of(Currency::Money) m.rep.should == 61725000 m.currency.code.should == :USD end it "should divide by numerics and return money" do m = @usd / 3 m.should be_kind_of(Currency::Money) m.rep.should == 41150000 m.currency.code.should == :USD end it "should divide by monies of the same currency and return numeric" do m = @usd / Currency::Money.new("41.15", :USD) m.should be_kind_of(Numeric) m.should be_close(3.0, 1.0e-8) end it "should divide by monies of different currencies and return numeric" do m = (@usd / @cad) m.should be_kind_of(Numeric) m.should be_close(Currency::Exchange::Rate::Source::Test.USD_CAD, 0.0001) end end it "pivot conversions" do # Using default get_rate cad = Currency::Money.new(123.45, :CAD) cad.should_not == nil eur = cad.convert(:EUR) eur.should_not == nil m = (eur.to_f / cad.to_f) m.should be_kind_of(Numeric) m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_CAD) * Currency::Exchange::Rate::Source::Test.USD_EUR m.should be_close(m_expected, 0.001) gbp = Currency::Money.new(123.45, :GBP) gbp.should_not == nil eur = gbp.convert(:EUR) eur.should_not == nil m = (eur.to_f / gbp.to_f) m.should be_kind_of(Numeric) m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_GBP) * Currency::Exchange::Rate::Source::Test.USD_EUR m.should be_close(m_expected, 0.001) end it "invalid currency code" do lambda {Currency::Money.new(123, :asdf)}.should raise_error(Currency::Exception::InvalidCurrencyCode) lambda {Currency::Money.new(123, 5)}.should raise_error(Currency::Exception::InvalidCurrencyCode) end it "time default" do Currency::Money.default_time = nil usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should == nil Currency::Money.default_time = Time.now usd = Currency::Money.new(123.45, :USD) usd.should_not == nil Currency::Money.default_time.should == usd.time end it "time now" do Currency::Money.default_time = :now usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should_not == nil sleep 1 usd2 = Currency::Money.new(123.45, :USD) usd2.should_not == nil usd2.time.should_not == nil (usd.time != usd2.time).should_not == nil Currency::Money.default_time = nil end it "time fixed" do Currency::Money.default_time = Time.new usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should_not == nil sleep 1 usd2 = Currency::Money.new(123.45, :USD) usd2.should_not == nil usd2.time.should_not == nil usd.time.should == usd2.time end end
acvwilson/currency
b44b25dea3fe929ce046b2fcd04db281cbef2511
VERSION BUMP
diff --git a/currency.gemspec b/currency.gemspec index aeb2ea8..7260459 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| s.name = %q{currency} - s.version = "0.5.0" + s.version = "0.5.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] s.date = %q{2008-11-14} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/currency_version.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_base_spec.rb", "spec/ar_column_spec.rb", "spec/ar_core_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.2.0} - s.summary = %q{currency 0.5.0} + s.summary = %q{currency 0.5.1} end \ No newline at end of file
acvwilson/currency
412df9fe73aa11b179693ff6f127b68d07346d8b
CHANGED: added rake spec related tasks ADDED: activesupport dependency (for precise rounding) CHANGED: made to_s work more better (but not all the way) (yet) CHANGED: ported more unit tests to spec
diff --git a/Rakefile b/Rakefile index 827c515..80e1d7d 100644 --- a/Rakefile +++ b/Rakefile @@ -1,95 +1,117 @@ # Rakefile for currency -*- ruby -*- # Adapted from RubyGems/Rakefile # For release " rake make_manifest rake update_version svn status rake package rake release VERSION=x.x.x rake svn_release rake publish_docs rake announce " ################################################################# require 'rubygems' +require 'spec/rake/spectask' +require 'rake/rdoctask' + +desc 'Default: run specs.' +task :default => :spec +Rake::Task[:default].prerequisites.clear + +desc 'Run specs' +Spec::Rake::SpecTask.new(:spec) do |t| + t.libs << 'lib' + t.pattern = 'spec/**/*_spec.rb' + t.verbose = true +end + +desc 'Generate documentation' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'doc' + rdoc.title = 'Currency' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README.txt') + rdoc.rdoc_files.include('lib/**/*.rb') +end ################################################################# # Release notes # def get_release_notes(relfile = "Releases.txt") release = nil notes = [ ] File.open(relfile) do |f| while ! f.eof && line = f.readline if md = /^== Release ([\d\.]+)/i.match(line) release = md[1] notes << line break end end while ! f.eof && line = f.readline if md = /^== Release ([\d\.]+)/i.match(line) break end notes << line end end [ release, notes.join('') ] end ################################################################# release, release_notes = get_release_notes ################################################################# # Misc Tasks --------------------------------------------------------- def egrep(pattern) Dir['**/*.rb'].each do |fn| count = 0 open(fn) do |f| while line = f.gets count += 1 if line =~ pattern puts "#{fn}:#{count}:#{line}" end end end end end desc "Look for TODO and FIXME tags in the code" task :todo do egrep /#.*(FIXME|TODO|TBD)/ end desc "Look for Debugging print lines" task :dbg do egrep /\bDBG|\bbreakpoint\b/ end desc "List all ruby files" task :rubyfiles do puts Dir['**/*.rb'].reject { |fn| fn =~ /^pkg/ } puts Dir['bin/*'].reject { |fn| fn =~ /CVS|.svn|(~$)|(\.rb$)/ } end task :make_manifest do open("Manifest.txt", "w") do |f| f.puts Dir['**/*'].reject { |fn| fn == 'email.txt' || ! test(?f, fn) || fn =~ /CVS|.svn|([#~]$)|(.gem$)|(^pkg\/)|(^doc\/)/ }.sort.join("\n") + "\n" end end diff --git a/lib/currency.rb b/lib/currency.rb index b4d9813..659a181 100644 --- a/lib/currency.rb +++ b/lib/currency.rb @@ -1,143 +1,143 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # # = Currency # # The Currency package provides an object-oriented model of: # # * currencies # * exchanges # * exchange rates # * exchange rate sources # * monetary values # # The core classes are: # # * Currency::Money - uses a scaled integer representation of a monetary value and performs accurate conversions to and from string values. # * Currency::Currency - provides an object-oriented representation of a currency. # * Currency::Exchange::Base - the base class for a currency exchange rate provider. # * Currency::Exchange::Rate::Source::Base - the base class for an on-demand currency exchange rate data provider. # * Currency::Exchange::Rate::Source::Provider - the base class for a bulk exchange rate data provider. # * Currency::Exchange::Rate - represents a exchange rate between two currencies. # # # The example below uses Currency::Exchange::Xe to automatically get # exchange rates from http://xe.com/ : # # require 'currency' # require 'currency/exchange/rate/deriver' # require 'currency/exchange/rate/source/xe' # require 'currency/exchange/rate/source/timed_cache' # # # Rate source initialization # provider = Currency::Exchange::Rate::Source::Xe.new # deriver = Currency::Exchange::Rate::Deriver.new(:source => provider) # cache = Currency::Exchange::Rate::Source::TimedCache.new(:source => deriver) # Currency::Exchange::Rate::Source.default = cache # # usd = Currency::Money('6.78', :USD) # puts "usd = #{usd.format}" # cad = usd.convert(:CAD) # puts "cad = #{cad.format}" # # == ActiveRecord Suppport # # This package also contains ActiveRecord support for money values: # # require 'currency' # require 'currency/active_record' # # class Entry < ActiveRecord::Base # money :amount # end # # In the example above, the entries.amount database column is an INTEGER that represents US cents. # The currency code of the money value can be stored in an additional database column or a default currency can be used. # # == Recent Enhancements # # === Storage and retrival of historical exchange rates # # * See Currency::Exchange::Rate::Source::Historical # * See Currency::Exchange::Rate::Source::Historical::Writer # # === Automatic derivation of rates from base rates. # # * See Currency::Exchange::Rate::Deriver # # === Rate caching # # * See Currency::Exchange::Rate::Source::TimedCache # # === Rate Providers # # * See Currency::Exchange::Rate::Source::Xe # * See Currency::Exchange::Rate::Source::NewYorkFed # * See Currency::Exchange::Rate::Source::TheFinancials # # === Customizable formatting and parsing # # * See Currency::Formatter # * See Currency::Parser # # == Future Enhancements # # * Support for inflationary rates within a currency, e.g. $10 USD in the year 1955 converted to 2006 USD. # # == SVN Repo # # svn checkout svn://rubyforge.org/var/svn/currency/currency/trunk # # == Examples # # See the examples/ and test/ directorys # # == Author # # Kurt Stephens http://kurtstephens.com # # == Support # # http://rubyforge.org/forum/forum.php?forum_id=7643 # # == Copyright # # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # # See LICENSE.txt for details. # module Currency # Use this function instead of Money#new: # # Currency::Money("12.34", :CAD) # # Do not do this: # # Currency::Money.new("12.34", :CAD) # # See Money#new. def self.Money(*opts) Money.new(*opts) end end $:.unshift(File.expand_path(File.dirname(__FILE__))) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'currency/currency_version' require 'currency/config' require 'currency/exception' require 'currency/money' require 'currency/currency' require 'currency/currency/factory' require 'currency/money' require 'currency/formatter' require 'currency/parser' require 'currency/exchange' require 'currency/exchange/rate' require 'currency/exchange/rate/deriver' require 'currency/exchange/rate/source' require 'currency/exchange/rate/source/test' require 'currency/exchange/time_quantitizer' require 'currency/core_extensions' - +require 'active_support' diff --git a/lib/currency/core_extensions.rb b/lib/currency/core_extensions.rb index 4a2b40f..47d3d68 100644 --- a/lib/currency/core_extensions.rb +++ b/lib/currency/core_extensions.rb @@ -1,48 +1,83 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. class Object # Exact conversion to Money representation value. def money(*opts) Currency::Money(self, *opts) end end class Integer # Exact conversion to Money representation value. def Money_rep(currency, time = nil) Integer(self * currency.scale) end end - +# module Asa +# module Rounding +# def self.included(base) #:nodoc: +# puts "included by #{base.inspect}" +# base.class_eval do +# alias_method :round_without_precision, :round +# alias_method :round, :round_with_precision +# end +# end +# +# # Rounds the float with the specified precision. +# # +# # x = 1.337 +# # x.round # => 1 +# # x.round(1) # => 1.3 +# # x.round(2) # => 1.34 +# def round_with_precision(precision = nil) +# precision.nil? ? round_without_precision : (self * (10 ** precision)).round / (10 ** precision).to_f +# end +# +# end +# end +# +# class Float +# include Asa::Rounding +# # Inexact conversion to Money representation value. +# def Money_rep(currency, time = nil) +# Integer(Currency::Config.current.float_ref_filter.call(self * currency.scale)) +# end +# end class Float # Inexact conversion to Money representation value. def Money_rep(currency, time = nil) Integer(Currency::Config.current.float_ref_filter.call(self * currency.scale)) end - def round_with_precision(precision = nil) - precision.nil? ? round_without_precision : (self * (10 ** precision)).round_without_precision / (10 ** precision).to_f - end - alias_method :round_without_precision, :round - alias_method :round, :round_with_precision + # def round_with_awesome_precision(precision = nil) + # # puts "self: #{self.inspect}" + # # puts "precision: #{precision.inspect}" + # # puts "round_without_precision: #{round_without_precision.inspect}" + # # puts "self * (10 ** precision): #{(self * (10 ** precision)).inspect}" + # # puts "(self * (10 ** precision)).round_without_precision: #{((self * (10 ** precision)).round_without_precision).inspect}" + # # self.to_s.to_f.round_without_precision + # precision.nil? ? round_without_awesome_precision : (self * (10 ** precision)).round_without_awesome_precision / (10 ** precision).to_f + # end + # alias_method :round_without_awesome_precision, :round + # alias_method :round, :round_with_awesome_precision end class String # Exact conversion to Money representation value. def Money_rep(currency, time = nil) x = currency.parse(self, :currency => currency, :time => time) x = x.rep if x.respond_to?(:rep) x end end diff --git a/lib/currency/currency.rb b/lib/currency/currency.rb index 58dd2bf..0e6ced4 100644 --- a/lib/currency/currency.rb +++ b/lib/currency/currency.rb @@ -1,175 +1,175 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # Represents a currency. # # Currency objects are created on-demand by Currency::Currency::Factory. # # See Currency.get method. # class Currency::Currency # Returns the ISO three-letter currency code as a symbol. # e.g. :USD, :CAD, etc. attr_reader :code # The Currency's scale factor. # e.g: the :USD scale factor is 100. attr_reader :scale # The Currency's scale factor. # e.g: the :USD scale factor is 2, where 10 ^ 2 == 100. attr_reader :scale_exp # Used by Formatter. attr_reader :format_right # Used by Formatter. attr_reader :format_left # The Currency's symbol. # e.g: USD symbol is '$' attr_accessor :symbol # The Currency's symbol as HTML. # e.g: EUR symbol is '&#8364;' (:html &#8364; :) or '&euro;' (:html &euro; :) attr_accessor :symbol_html # The default Formatter. attr_accessor :formatter # The default parser. attr_accessor :parser # Create a new currency. # This should only be called from Currency::Currency::Factory. def initialize(code, symbol = nil, scale = 1000000) self.code = code self.symbol = symbol self.scale = scale @formatter = @parser = nil end # Returns the Currency object from the default Currency::Currency::Factory # by its three-letter uppercase Symbol, such as :USD, or :CAD. def self.get(code) # $stderr.puts "#{self}.get(#{code.inspect})" return nil unless code return code if code.kind_of?(::Currency::Currency) Factory.default.get_by_code(code) end # Internal method for converting currency codes to internal # Symbol format. def self.cast_code(x) x = x.upcase.intern if x.kind_of?(String) raise ::Currency::Exception::InvalidCurrencyCode, x unless x.kind_of?(Symbol) raise ::Currency::Exception::InvalidCurrencyCode, x unless x.to_s.length == 3 x end # Returns the hash of the Currency's code. def hash @code.hash end # Returns true if the Currency's are equal. def eql?(x) self.class == x.class && @code == x.code end # Returns true if the Currency's are equal. def ==(x) self.class == x.class && @code == x.code end # Clients should never call this directly. def code=(x) x = self.class.cast_code(x) unless x.nil? @code = x #$stderr.puts "#{self}.code = #{@code}"; x end # Clients should never call this directly. def scale=(x) @scale = x return x if x.nil? @scale_exp = Integer(Math.log10(@scale)); @format_right = - @scale_exp @format_left = @format_right - 1 x end # Parse a Money string in this Currency. # # See Currency::Parser#parse. # def parse(str, *opt) parser_or_default.parse(str, *opt) end def parser_or_default (@parser || ::Currency::Parser.default) end # Formats the Money value as a string using the current Formatter. # See Currency::Formatter#format. def format(m, *opt) - formatter_or_default.format(m, *opt) + formatter_or_default.format(m, *opt) end def formatter_or_default (@formatter || ::Currency::Formatter.default) end # Returns the Currency code as a String. def to_s @code.to_s end # Returns the default Factory's currency. def self.default Factory.default.currency end # Sets the default Factory's currency. def self.default=(x) x = self.get(x) unless x.kind_of?(self) Factory.default.currency = x end # If selector is [A-Z][A-Z][A-Z], load the currency via Factory.default. # # Currency::Currency.USD # => #<Currency::Currency:0xb7d0917c @formatter=nil, @scale_exp=2, @scale=100, @symbol="$", @format_left=-3, @code=:USD, @parser=nil, @format_right=-2> # def self.method_missing(sel, *args, &blk) if args.size == 0 && (! block_given?) && /^[A-Z][A-Z][A-Z]$/.match(sel.to_s) Factory.default.get_by_code(sel) else super end end end # class diff --git a/lib/currency/formatter.rb b/lib/currency/formatter.rb index 77cdaff..b12da1d 100644 --- a/lib/currency/formatter.rb +++ b/lib/currency/formatter.rb @@ -1,300 +1,310 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'rss/rss' # Time#xmlschema # This class formats a Money value as a String. # Each Currency has a default Formatter. class Currency::Formatter # The underlying object for Currency::Formatter#format. # This object is cloned and initialized with strings created # from Formatter#format. # It handles the Formatter#format string interpolation. class Template @@empty_hash = { } @@empty_hash.freeze # The template string. attr_accessor :template # The Currency::Money object being formatted. attr_accessor :money # The Currency::Currency object being formatted. attr_accessor :currency # The sign: '-' or nil. attr_accessor :sign # The whole part of the value, with thousands_separator or nil. attr_accessor :whole # The fraction part of the value, with decimal_separator or nil. attr_accessor :fraction # The currency symbol or nil. attr_accessor :symbol # The currency code or nil. attr_accessor :code # The time or nil. attr_accessor :time def initialize(opts = @@empty_hash) @template = @template_proc = nil opts.each_pair{ | k, v | self.send("#{k}=", v) } end # Sets the template string and uncaches the template_proc. def template=(x) if @template != x @template_proc = nil end @template = x end # Defines a the self._format template procedure using # the template as a string to be interpolated. def template_proc(template = @template) return @template_proc if @template_proc @template_proc = template || '' # @template_proc = @template_proc.gsub(/[\\"']/) { | x | "\\" + x } @template_proc = "def self._format; \"#{@template_proc}\"; end" self.instance_eval @template_proc @template_proc end # Formats the current state using the template. def format template_proc _format end end # Defaults to ',' attr_accessor :thousands_separator # Defaults to '.' attr_accessor :decimal_separator # If true, insert _thousands_separator_ between each 3 digits in the whole value. attr_accessor :thousands # If true, append _decimal_separator_ and decimal digits after whole value. attr_accessor :cents # If true, prefix value with currency symbol. attr_accessor :symbol # If true, append currency code. attr_accessor :code # If true, append the time. attr_accessor :time # The number of fractional digits in the time. # Defaults to 4. attr_accessor :time_fractional_digits # If true, use html formatting. # # Currency::Money(12.45, :EUR).to_s(:html => true; :code => true) # => "&#8364;12.45 <span class=\"currency_code\">EUR</span>" attr_accessor :html # A template string used to format a money value. # Defaults to: # # '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}#{time && " "}#{time}' attr_accessor :template # Set the decimal_places # Defaults to: nil attr_accessor :decimals # If passed true, formats for an input field (i.e.: as a number). def as_input_value=(x) if x self.thousands_separator = '' self.decimal_separator = '.' self.thousands = false self.cents = true self.symbol = false self.code = false self.html = false self.time = false self.time_fractional_digits = nil end x end @@default = nil # Get the default Formatter. def self.default @@default || self.new end # Set the default Formatter. def self.default=(x) @@default = x end def initialize(opt = { }) @thousands_separator = ',' @decimal_separator = '.' @thousands = true @cents = true @symbol = true @code = false @html = false @time = false @time_fractional_digits = 4 @template = '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}#{time && " "}#{time}' @template_object = nil @decimals = nil opt.each_pair{ | k, v | self.send("#{k}=", v) } end def currency=(x) # :nodoc: # DO NOTHING! end # Sets the template and the Template#template. def template=(x) if @template_object @template_object.template = x end @template = x end # Returns the Template object. def template_object return @template_object if @template_object @template_object = Template.new @template_object.template = @template if @template # $stderr.puts "template.template = #{@template_object.template.inspect}" @template_object.template_proc # pre-cache before clone. @template_object end def _format(m, currency = nil, time = nil) # :nodoc: # Get currency. currency ||= m.currency # Get time. time ||= m.time # set decimal places @decimals ||= currency.scale_exp # Setup template tmpl = self.template_object.clone # $stderr.puts "template.template = #{tmpl.template.inspect}" tmpl.money = m tmpl.currency = currency # Get scaled integer representation for this Currency. # $stderr.puts "m.currency = #{m.currency}, currency => #{currency}" x = m.Money_rep(currency) # Remove sign. x = - x if ( neg = x < 0 ) tmpl.sign = neg ? '-' : nil # Convert to String. x = x.to_s # Keep prefixing "0" until filled to scale. while ( x.length <= currency.scale_exp ) x = "0" + x end # Insert decimal place. whole = x[0 .. currency.format_left] fraction = x[currency.format_right .. -1] # Round the fraction to the supplied number of decimal places - fraction = ((fraction.to_f / currency.scale).round(@decimals) * (10 ** @decimals)).to_i.to_s + fraction = (fraction.to_f / currency.scale).round(@decimals).to_s[2..-1] + # raise "decimals: #{@decimals}, scale_exp: #{currency.scale_exp}, x is: #{x.inspect}, currency.scale_exp is #{currency.scale_exp.inspect}, fraction: #{fraction.inspect}" + while ( fraction.length < @decimals ) + fraction = fraction + "0" + end + + + # raise "x is: #{x.inspect}, currency.scale_exp is #{currency.scale_exp.inspect}, fraction: #{fraction.inspect}" + # fraction = ((fraction.to_f / currency.scale).round(decimals) * (10 ** decimals)).to_i.to_s # Do thousands. x = whole if @thousands && (@thousands_separator && ! @thousands_separator.empty?) x.reverse! x.gsub!(/(\d\d\d)/) {|y| y + @thousands_separator} x.sub!(/#{@thousands_separator}$/,'') x.reverse! end # Put whole and fractional parts. tmpl.whole = x tmpl.fraction = @cents && @decimal_separator ? @decimal_separator + fraction : nil # Add symbol? tmpl.symbol = @symbol ? ((@html && currency.symbol_html) || currency.symbol) : nil # Add currency code. tmpl.code = @code ? _format_Currency(currency) : nil # Add time. tmpl.time = @time && time ? _format_Time(time) : nil # Ask template to format the components. tmpl.format end def _format_Currency(c) # :nodoc: x = '' x << '<span class="currency_code">' if @html x << c.code.to_s x << '</span>' if @html x end def _format_Time(t) # :nodoc: x = '' x << t.getutc.xmlschema(@time_fractional_digits) if t x end @@empty_hash = { } @@empty_hash.freeze # Format a Money object as a String. # # m = Money.new("1234567.89") # m.to_s(:code => true, :symbol => false) # => "1,234,567.89 USD" # def format(m, opt = @@empty_hash) + # raise "huh: #{opt.inspect}" + fmt = self unless opt.empty? fmt = fmt.clone opt.each_pair{ | k, v | fmt.send("#{k}=", v) } end # $stderr.puts "format(opt = #{opt.inspect})" fmt._format(m, opt[:currency]) # Allow override of current currency. end end # class diff --git a/lib/currency/money.rb b/lib/currency/money.rb index 4ec8daa..b77d646 100644 --- a/lib/currency/money.rb +++ b/lib/currency/money.rb @@ -1,296 +1,298 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # # Represents an amount of money in a particular currency. # # A Money object stores its value using a scaled Integer representation # and a Currency object. # # A Money object also has a time, which is used in conversions # against historical exchange rates. # class Currency::Money include Comparable @@default_time = nil def self.default_time @@default_time end def self.default_time=(x) @@default_time = x end @@empty_hash = { } @@empty_hash.freeze # # DO NOT CALL THIS DIRECTLY: # # See Currency.Money() function. # # Construct a Money value object # from a pre-scaled external representation: # where x is a Float, Integer, String, etc. # # If a currency is not specified, Currency.default is used. # # x.Money_rep(currency) # # is invoked to coerce x into a Money representation value. # # For example: # # 123.Money_rep(:USD) => 12300 # # Because the USD Currency object has a #scale of 100 # # See #Money_rep(currency) mixin. # def initialize(x, currency = nil, time = nil) opts ||= @@empty_hash # Set ivars. currency = ::Currency::Currency.get(currency) @currency = currency @time = time || ::Currency::Money.default_time @time = ::Currency::Money.now if @time == :now if x.kind_of?(String) if currency m = currency.parser_or_default.parse(x, :currency => currency) else m = ::Currency::Parser.default.parse(x) end @currency = m.currency unless @currency @time = m.time if m.time @rep = m.rep else @currency = ::Currency::Currency.default unless @currency @rep = x.Money_rep(@currency) end end # Returns a Time.new # Can be modifed for special purposes. def self.now Time.new end # Compatibility with Money package. def self.us_dollar(x) self.new(x, :USD) end # Compatibility with Money package. def cents @rep end # Construct from post-scaled internal representation. def self.new_rep(r, currency = nil, time = nil) x = self.new(0, currency, time) x.set_rep(r) x end # Construct from post-scaled internal representation. # using the same currency. # # x = Currency.Money("1.98", :USD) # x.new_rep(123) => USD $1.23 # # time defaults to self.time. def new_rep(r, time = nil) time ||= @time x = self.class.new(0, @currency, time) x.set_rep(r) x end # Do not call this method directly. # CLIENTS SHOULD NEVER CALL set_rep DIRECTLY. # You have been warned in ALL CAPS. def set_rep(r) # :nodoc: r = r.to_i unless r.kind_of?(Integer) @rep = r end # Do not call this method directly. # CLIENTS SHOULD NEVER CALL set_time DIRECTLY. # You have been warned in ALL CAPS. def set_time(time) # :nodoc: @time = time end # Returns the Money representation (usually an Integer). def rep @rep end # Get the Money's Currency. def currency @currency end # Get the Money's time. def time @time end # Convert Money to another Currency. # currency can be a Symbol or a Currency object. # If currency is nil, the Currency.default is used. def convert(currency, time = nil) currency = ::Currency::Currency.default if currency.nil? currency = ::Currency::Currency.get(currency) unless currency.kind_of?(Currency) if @currency == currency self else time = self.time if time == :money ::Currency::Exchange::Rate::Source.current.convert(self, currency, time) end end # Hash for hash table: both value and currency. # See #eql? below. def hash @rep.hash ^ @currency.hash end # True if money values have the same value and currency. def eql?(x) self.class == x.class && @rep == x.rep && @currency == x.currency end # True if money values have the same value and currency. def ==(x) self.class == x.class && @rep == x.rep && @currency == x.currency end # Compares Money values. # Will convert x to self.currency before comparision. def <=>(x) if @currency == x.currency @rep <=> x.rep else @rep <=> convert(@currency, @time).rep end end # - Money => Money # # Negates a Money value. def -@ new_rep(- @rep) end # Money + (Money | Number) => Money # # Right side may be coerced to left side's Currency. def +(x) new_rep(@rep + x.Money_rep(@currency)) end # Money - (Money | Number) => Money # # Right side may be coerced to left side's Currency. def -(x) new_rep(@rep - x.Money_rep(@currency)) end # Money * Number => Money # # Right side must be Number. def *(x) new_rep(@rep * x) end # Money / Money => Float (ratio) # Money / Number => Money # # Right side must be Money or Number. # Right side Integers are not coerced to Float before # division. def /(x) if x.kind_of?(self.class) (@rep.to_f) / (x.Money_rep(@currency).to_f) else new_rep(@rep / x) end end # Formats the Money value as a String using the Currency's Formatter. def format(*opt) @currency.format(self, *opt) end # Formats the Money value as a String. def to_s(*opt) + # raise "huh: #{opt.inspect}" + @currency.format(self, *opt) end # Coerces the Money's value to a Float. # May cause loss of precision. def to_f Float(@rep) / @currency.scale end # Coerces the Money's value to an Integer. # May cause loss of precision. def to_i @rep / @currency.scale end # True if the Money's value is zero. def zero? @rep == 0 end # True if the Money's value is greater than zero. def positive? @rep > 0 end # True if the Money's value is less than zero. def negative? @rep < 0 end # Returns the Money's value representation in another currency. def Money_rep(currency, time = nil) # Attempt conversion? if @currency != currency || (time && @time != time) self.convert(currency, time).rep # raise ::Currency::Exception::Generic, "Incompatible Currency: #{@currency} != #{currency}" else @rep end end # Basic inspection, with symbol, currency code and time. # The standard #inspect method is available as #inspect_deep. def inspect(*opts) self.format(:symbol => true, :code => true, :time => true) end # How to alias a method defined in an object superclass in a different class: define_method(:inspect_deep, Object.instance_method(:inspect)) # How call a method defined in a superclass from a method with a different name: # def inspect_deep(*opts) # self.class.superclass.instance_method(:inspect).bind(self).call # end end # class diff --git a/spec/ar_base_spec.rb b/spec/ar_base_spec.rb deleted file mode 100644 index a4f1539..0000000 --- a/spec/ar_base_spec.rb +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> -# See LICENSE.txt for details. - -require 'test/test_base' -require 'currency' - -require 'rubygems' -require 'active_record' -require 'active_record/migration' -require 'currency/active_record' - -AR_M = ActiveRecord::Migration -AR_B = ActiveRecord::Base - -module Currency - -class ArTestBase < TestBase - - ################################################## - - before do - super - AR_B.establish_connection(database_spec) - - # Subclasses can override this. - @currency_test_migration ||= nil - @currency_test ||= nil - - # schema_down - - schema_up - end - - - def teardown - super - # schema_down - end - - - def database_spec - # TODO: Get from ../config/database.yml:test - # Create test database on: - - # MYSQL: - # - # sudo mysqladmin create test; - # sudo mysql - # grant all on test.* to test@localhost identified by 'test'; - # flush privileges; - - # POSTGRES: - # - # CREATE USER test PASSWORD 'test'; - # CREATE DATABASE test WITH OWNER = test; - # - - @database_spec = { - :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', - :host => ENV['TEST_DB_HOST'] || 'localhost', - :username => ENV['TEST_DB_USER'] || 'test', - :password => ENV['TEST_DB_PASS'] || 'test', - :database => ENV['TEST_DB_TEST'] || 'test' - } - end - - - def schema_up - return unless @currency_test_migration - begin - @currency_test_migration.migrate(:up) - rescue Object =>e - $stderr.puts "Warning: #{e}" - end - end - - - def schema_down - return unless @currency_test_migration - begin - @currency_test_migration.migrate(:down) - rescue Object => e - $stderr.puts "Warning: #{e}" - end - end - - - ################################################## - # Scaffold - # - - def insert_records - delete_records - - @currency_test.reset_column_information - - @usd = @currency_test.new(:name => '#1: USD', :amount => Money.new("12.34", :USD)) - @usd.save - - @cad = @currency_test.new(:name => '#2: CAD', :amount => Money.new("56.78", :CAD)) - @cad.save - end - - - def delete_records - @currency_test.destroy_all - end - - - ################################################## - - - def assert_equal_money(a,b) - a.should_not be_nil - b.should_not be_nil - # Make sure a and b are not the same object. - b.object_id.should_not == a.object_id - b.id.should == a.id - a.amount.should.not == nil - a.amount.should be_kind_of(Money) - b.amount.should.not == nil - b.amount.should be_kind_of(Money) - # Make sure that what gets stored in the database comes back out - # when converted back to the original currency. - b.amount.rep.should == a.amount.convert(b.amount.currency).rep - end - - - def assert_equal_currency(a,b) - assert_equal_money a, b - - b.amount.rep.should == a.amount.rep - b.amount.currency.should == a.amount.currency - b.amount.currency.code.should == a.amount.currency.code - - end -end - -end # module - diff --git a/spec/ar_column_spec.rb b/spec/ar_column_spec.rb index 1be91a2..e8d5b66 100644 --- a/spec/ar_column_spec.rb +++ b/spec/ar_column_spec.rb @@ -1,69 +1,76 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. -require 'test/ar_test_core' -require 'currency' +# require 'test/ar_test_core' +# require 'currency' +# +# require 'rubygems' +# require 'active_record' +# require 'active_record/migration' +# require 'currency/active_record' -require 'rubygems' -require 'active_record' -require 'active_record/migration' -require 'currency/active_record' +require File.dirname(__FILE__) + '/ar_spec_helper' -module Currency - -class ArFieldTest < ArTestCore +# module Currency +# +# class ArFieldTest < ArTestCore ################################################## # Basic CurrenyTest AR::B class # TABLE_NAME = 'currency_column_test' class CurrencyColumnTestMigration < AR_M def self.up create_table TABLE_NAME.intern do |t| t.column :name, :string t.column :amount, :integer # Money t.column :amount_currency, :string, :size => 3 # Money.currency.code end end def self.down drop_table TABLE_NAME.intern end end class CurrencyColumnTest < AR_B set_table_name TABLE_NAME attr_money :amount, :currency_column => true end ################################################## - before do - @currency_test_migration ||= CurrencyColumnTestMigration - @currency_test ||= CurrencyColumnTest - super - end - def teardown - super - end + # def teardown + # super + # end ################################################## +describe "ActiveRecord macros" do + before(:all) do + AR_B.establish_connection(database_spec) + @currency_test_migration ||= CurrencyColumnTestMigration + @currency_test ||= CurrencyColumnTest + # schema_down + schema_up + end + + after(:all) do + # schema_down + end it "field" do insert_records - usd = @currency_test.find(@usd.id).should.not == nil + usd = @currency_test.find(@usd.id) + usd.should_not be_nil assert_equal_currency usd, @usd - cad = @currency_test.find(@cad.id).should.not == nil + cad = @currency_test.find(@cad.id) + cad.should_not be_nil assert_equal_currency cad, @cad end - end - -end # module - diff --git a/spec/ar_core_spec.rb b/spec/ar_core_spec.rb index f7ee92d..4286f10 100644 --- a/spec/ar_core_spec.rb +++ b/spec/ar_core_spec.rb @@ -1,64 +1,68 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. + +# ================================================================= +# = TODO: IS THIS STUFF ACTUALLY NEEDED? IF SO, MOVE TO AR HELPER = +# ================================================================= require 'test/ar_test_base' module Currency class ArTestCore < ArTestBase ################################################## # Basic CurrenyTest AR::B class # TABLE_NAME = 'currency_test' class CurrencyTestMigration < AR_M def self.up create_table TABLE_NAME.intern do |t| t.column :name, :string t.column :amount, :integer # Money end end def self.down drop_table TABLE_NAME.intern end end class CurrencyTest < AR_B set_table_name TABLE_NAME attr_money :amount end ################################################## before do @currency_test_migration ||= CurrencyTestMigration @currency_test ||= CurrencyTest super end def teardown super # schema_down end ################################################## # # it "insert" do insert_records end end end # module diff --git a/spec/ar_simple_spec.rb b/spec/ar_simple_spec.rb index 09d7229..da5e868 100644 --- a/spec/ar_simple_spec.rb +++ b/spec/ar_simple_spec.rb @@ -1,31 +1,23 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# Copyright (C) 2008 Asa Wilson <acvwilson(at)gmail.com> # See LICENSE.txt for details. -require 'test/ar_test_core' -require 'currency' - -require 'rubygems' -require 'active_record' -require 'active_record/migration' -require 'currency/active_record' - -module Currency - -class ArSimpleTest < ArTestCore +require File.dirname(__FILE__) + '/ar_spec_helper' +describe Currency::ActiveRecord do it "simple" do + # TODO: move insert_records into a before block? insert_records - usd = @currency_test.find(@usd.id).should.not == nil + usd = @currency_test.find(@usd.id) + usd.should_not be_nil assert_equal_currency usd, @usd - cad = @currency_test.find(@cad.id).should.not == nil + cad = @currency_test.find(@cad.id) + cad.should_not == nil assert_equal_money cad, @cad - :USD.should == cad.amount.currency.code + cad.amount.currency.code.should == :USD end - end -end # module - diff --git a/spec/ar_spec_helper.rb b/spec/ar_spec_helper.rb new file mode 100644 index 0000000..3a42558 --- /dev/null +++ b/spec/ar_spec_helper.rb @@ -0,0 +1,125 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# Copyright (C) 2008 Asa Wilson <acvwilson(at)gmail.com> +# See LICENSE.txt for details. + +require File.dirname(__FILE__) + '/spec_helper' + +require 'active_record' +require 'active_record/migration' +require File.dirname(__FILE__) + '/../lib/currency/active_record' + +AR_M = ActiveRecord::Migration +AR_B = ActiveRecord::Base + +def ar_setup + AR_B.establish_connection(database_spec) + + # Subclasses can override this. + @currency_test_migration ||= nil + @currency_test ||= nil + + # schema_down + + schema_up + +end + +def database_spec + # TODO: Get from ../config/database.yml:test + # Create test database on: + + # MYSQL: + # + # sudo mysqladmin create test; + # sudo mysql + # grant all on test.* to test@localhost identified by 'test'; + # flush privileges; + + # POSTGRES: + # + # CREATE USER test PASSWORD 'test'; + # CREATE DATABASE test WITH OWNER = test; + # + + # @database_spec = { + # :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', + # :host => ENV['TEST_DB_HOST'] || 'localhost', + # :username => ENV['TEST_DB_USER'] || 'test', + # :password => ENV['TEST_DB_PASS'] || 'test', + # :database => ENV['TEST_DB_TEST'] || 'test' + # } + + @database_spec = { + :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', + :host => ENV['TEST_DB_HOST'] || 'localhost', + :username => ENV['TEST_DB_USER'] || 'root', + :password => ENV['TEST_DB_PASS'] || '', + :database => ENV['TEST_DB_TEST'] || 'currency_gem_test' + } + +end + +def schema_up + return unless @currency_test_migration + begin + @currency_test_migration.migrate(:up) + rescue Object =>e + $stderr.puts "Warning: #{e}" + end +end + +def schema_down + return unless @currency_test_migration + begin + @currency_test_migration.migrate(:down) + rescue Object => e + $stderr.puts "Warning: #{e}" + end +end + +################################################## +# Scaffold +# + +def insert_records + delete_records + + @currency_test.reset_column_information + + @usd = @currency_test.new(:name => '#1: USD', :amount => Currency::Money.new("12.34", :USD)) + @usd.save + + @cad = @currency_test.new(:name => '#2: CAD', :amount => Currency::Money.new("56.78", :CAD)) + @cad.save +end + +def delete_records + @currency_test.destroy_all +end + +################################################## + +def assert_equal_money(a,b) + a.should_not be_nil + b.should_not be_nil + # Make sure a and b are not the same object. + b.object_id.should_not == a.object_id + b.id.should == a.id + a.amount.should.not == nil + a.amount.should be_kind_of(Money) + b.amount.should.not == nil + b.amount.should be_kind_of(Money) + # Make sure that what gets stored in the database comes back out + # when converted back to the original currency. + b.amount.rep.should == a.amount.convert(b.amount.currency).rep +end + + +def assert_equal_currency(a,b) + assert_equal_money a, b + + b.amount.rep.should == a.amount.rep + b.amount.currency.should == a.amount.currency + b.amount.currency.code.should == a.amount.currency.code + +end \ No newline at end of file diff --git a/spec/money_spec.rb b/spec/money_spec.rb index 0e44ef3..e1d0469 100644 --- a/spec/money_spec.rb +++ b/spec/money_spec.rb @@ -1,347 +1,355 @@ require File.dirname(__FILE__) + '/spec_helper' describe Currency::Money do it "create" do m = Currency::Money.new(1.99) m.should be_kind_of(Currency::Money) Currency::Currency.default.should == m.currency :USD.should == m.currency.code end describe "object money method" do it "works with a float" do m = 1.99.money(:USD) m.should be_kind_of(Currency::Money) :USD.should == m.currency.code m.rep.should == 1990000 end it "works with a FixNum" do m = 199.money(:CAD) m.should be_kind_of(Currency::Money) :CAD.should == m.currency.code m.rep.should == 199000000 end it "works with a string" do m = "13.98".money(:CAD) m.should be_kind_of(Currency::Money) :CAD.should == m.currency.code m.rep.should == 13980000 end it "works with a string again" do m = "45.99".money(:EUR) m.should be_kind_of(Currency::Money) :EUR.should == m.currency.code m.rep.should == 45990000 end + + it "creates money objects from strings" do + "12.0001".money(:USD).to_s.should == "$12.0001" + # "12.000108".money(:USD).to_s(:thousands => false, :decimals => 5).should == "$12.00011" + @money = Currency::Money.new_rep(1234567890000, :USD, nil) + + Currency::Money.new("12.000108").to_s(:thousands => false, :decimals => 5).should == "$12.00011" + end end def zero_money @zero_money ||= Currency::Money.new(0) end it "zero" do zero_money.negative?.should_not == true zero_money.zero?.should_not == nil zero_money.positive?.should_not == true end def negative_money @negative_money ||= Currency::Money.new(-1.00, :USD) end it "negative" do negative_money.negative?.should_not == nil negative_money.zero?.should_not == true negative_money.positive?.should_not == true end def positive_money @positive_money ||= Currency::Money.new(2.99, :USD) end it "positive" do positive_money.negative?.should_not == true positive_money.zero?.should_not == true positive_money.positive?.should_not == nil end it "relational" do n = negative_money z = zero_money p = positive_money (n.should < p) (n > p).should_not == true (p < n).should_not == true (p.should > n) (p != n).should_not == nil (z.should <= z) (z.should >= z) (z.should <= p) (n.should <= z) (z.should >= n) n.should == n p.should == p z.should == zero_money end it "compare" do n = negative_money z = zero_money p = positive_money (n <=> p).should == -1 (p <=> n).should == 1 (p <=> z).should == 1 (n <=> n).should == 0 (z <=> z).should == 0 (p <=> p).should == 0 end it "rep" do m = Currency::Money.new(123, :USD) m.should_not == nil m.rep.should == 123000000 m = Currency::Money.new(123.45, :USD) m.should_not == nil m.rep.should == 123450000 m = Currency::Money.new("123.456", :USD) m.should_not == nil m.rep.should == 123456000 end it "convert" do m = Currency::Money.new("123.456", :USD) m.should_not == nil m.rep.should == 123456000 m.to_i.should == 123 m.to_f.should == 123.456 m.to_s.should == "$123.456000" end it "eql" do usd1 = Currency::Money.new(123, :USD) usd1.should_not == nil usd2 = Currency::Money.new("123", :USD) usd2.should_not == nil usd1.currency.code.should == :USD usd2.currency.code.should == :USD usd2.rep.should == usd1.rep usd1.should == usd2 end it "not eql" do usd1 = Currency::Money.new(123, :USD) usd1.should_not == nil usd2 = Currency::Money.new("123.01", :USD) usd2.should_not == nil usd1.currency.code.should == :USD usd2.currency.code.should == :USD usd2.rep.should_not == usd1.rep (usd1 != usd2).should_not == nil ################ # currency != # rep == usd = Currency::Money.new(123, :USD) usd.should_not == nil cad = Currency::Money.new(123, :CAD) cad.should_not == nil usd.currency.code.should == :USD cad.currency.code.should == :CAD cad.rep.should == usd.rep (usd.currency != cad.currency).should_not == nil (usd != cad).should_not == nil end describe "operations" do before(:each) do @usd = Currency::Money.new(123.45, :USD) @cad = Currency::Money.new(123.45, :CAD) end it "should work" do @usd.should_not == nil @cad.should_not == nil end it "handle negative money" do # - Currency::Money => Currency::Money (- @usd).rep.should == -123450000 (- @usd).currency.code.should == :USD (- @cad).rep.should == -123450000 (- @cad).currency.code.should == :CAD end it "should add monies of the same currency" do m = (@usd + @usd) m.should be_kind_of(Currency::Money) m.rep.should == 246900000 m.currency.code.should == :USD end it "should add monies of different currencies and return USD" do m = (@usd + @cad) m.should be_kind_of(Currency::Money) m.rep.should == 228890724 m.currency.code.should == :USD end it "should add monies of different currencies and return CAD" do m = (@cad + @usd) m.should be_kind_of(Currency::Money) m.rep.should == 267985260 m.currency.code.should == :CAD end it "should subtract monies of the same currency" do m = (@usd - @usd) m.should be_kind_of(Currency::Money) m.rep.should == 0 m.currency.code.should == :USD end it "should subtract monies of different currencies and return USD" do m = (@usd - @cad) m.should be_kind_of(Currency::Money) m.rep.should == 18009276 m.currency.code.should == :USD end it "should subtract monies of different currencies and return CAD" do m = (@cad - @usd) m.should be_kind_of(Currency::Money) m.rep.should == -21085260 m.currency.code.should == :CAD end it "should multiply by numerics and return money" do m = (@usd * 0.5) m.should be_kind_of(Currency::Money) m.rep.should == 61725000 m.currency.code.should == :USD end it "should divide by numerics and return money" do m = @usd / 3 m.should be_kind_of(Currency::Money) m.rep.should == 41150000 m.currency.code.should == :USD end it "should divide by monies of the same currency and return numeric" do m = @usd / Currency::Money.new("41.15", :USD) m.should be_kind_of(Numeric) m.should be_close(3.0, 1.0e-8) end it "should divide by monies of different currencies and return numeric" do m = (@usd / @cad) m.should be_kind_of(Numeric) m.should be_close(Currency::Exchange::Rate::Source::Test.USD_CAD, 0.0001) end end it "pivot conversions" do # Using default get_rate cad = Currency::Money.new(123.45, :CAD) cad.should_not == nil eur = cad.convert(:EUR) eur.should_not == nil m = (eur.to_f / cad.to_f) m.should be_kind_of(Numeric) m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_CAD) * Currency::Exchange::Rate::Source::Test.USD_EUR m.should be_close(m_expected, 0.001) gbp = Currency::Money.new(123.45, :GBP) gbp.should_not == nil eur = gbp.convert(:EUR) eur.should_not == nil m = (eur.to_f / gbp.to_f) m.should be_kind_of(Numeric) m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_GBP) * Currency::Exchange::Rate::Source::Test.USD_EUR m.should be_close(m_expected, 0.001) end it "invalid currency code" do lambda {Currency::Money.new(123, :asdf)}.should raise_error(Currency::Exception::InvalidCurrencyCode) lambda {Currency::Money.new(123, 5)}.should raise_error(Currency::Exception::InvalidCurrencyCode) end it "time default" do Currency::Money.default_time = nil usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should == nil Currency::Money.default_time = Time.now usd = Currency::Money.new(123.45, :USD) usd.should_not == nil Currency::Money.default_time.should == usd.time end it "time now" do Currency::Money.default_time = :now usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should_not == nil sleep 1 usd2 = Currency::Money.new(123.45, :USD) usd2.should_not == nil usd2.time.should_not == nil (usd.time != usd2.time).should_not == nil Currency::Money.default_time = nil end it "time fixed" do Currency::Money.default_time = Time.new usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should_not == nil sleep 1 usd2 = Currency::Money.new(123.45, :USD) usd2.should_not == nil usd2.time.should_not == nil usd.time.should == usd2.time end end
acvwilson/currency
02441de28f0ec3b5d077fb207b931d32133d065c
CHANGED: gem setup code cleanup (no more svn)
diff --git a/Rakefile b/Rakefile index cee1b87..827c515 100644 --- a/Rakefile +++ b/Rakefile @@ -1,167 +1,95 @@ # Rakefile for currency -*- ruby -*- # Adapted from RubyGems/Rakefile # For release " rake make_manifest rake update_version svn status rake package rake release VERSION=x.x.x rake svn_release rake publish_docs rake announce " ################################################################# require 'rubygems' -require 'hoe' - -PKG_Name = 'Currency' -PKG_DESCRIPTION = %{Currency models currencies, monetary values, foreign exchanges rates. -Pulls live and historical rates from http://xe.com/, http://newyorkfed.org/, http://thefinancials.com/. -Can store/retrieve historical rate data from database using ActiveRecord. -Can store/retrieve Money values using ActiveRecord. - -For more details, see: - -http://rubyforge.org/projects/currency/ -http://currency.rubyforge.org/ -http://currency.rubyforge.org/files/README_txt.html - -} ################################################################# # Release notes # def get_release_notes(relfile = "Releases.txt") release = nil notes = [ ] File.open(relfile) do |f| while ! f.eof && line = f.readline if md = /^== Release ([\d\.]+)/i.match(line) release = md[1] notes << line break end end while ! f.eof && line = f.readline if md = /^== Release ([\d\.]+)/i.match(line) break end notes << line end end [ release, notes.join('') ] end ################################################################# -PKG_NAME = PKG_Name.gsub(/[a-z][A-Z]/) {|x| "#{x[0,1]}_#{x[1,1]}"}.downcase - -PKG_SVN_ROOT="svn+ssh://rubyforge.org/var/svn/#{PKG_NAME}/#{PKG_NAME}" - release, release_notes = get_release_notes -hoe = Hoe.new(PKG_Name.downcase, release) do |p| - p.author = 'Kurt Stephens' - p.description = PKG_DESCRIPTION - p.email = "ruby-#{PKG_NAME}@umleta.com" - p.summary = p.description - p.changes = release_notes - p.url = "http://rubyforge.org/projects/#{PKG_NAME}" - - p.test_globs = ['test/**/*.rb'] -end - -PKG_VERSION = hoe.version - -################################################################# -# Version file -# - -def announce(msg='') - STDERR.puts msg -end - -version_rb = "lib/#{PKG_NAME}/#{PKG_NAME}_version.rb" - -task :update_version do - announce "Updating #{PKG_Name} version to #{PKG_VERSION}: #{version_rb}" - open(version_rb, "w") do |f| - f.puts "module #{PKG_Name}" - f.puts " #{PKG_Name}Version = '#{PKG_VERSION}'" - f.puts "end" - f.puts "# DO NOT EDIT" - f.puts "# This file is auto-generated by build scripts." - f.puts "# See: rake update_version" - end - if ENV['RELTEST'] - announce "Release Task Testing, skipping commiting of new version" - else - sh %{svn commit -m "Updated to version #{PKG_VERSION}" #{version_rb} Releases.txt ChangeLog Rakefile Manifest.txt} - end -end - -task version_rb => :update_version - ################################################################# -# SVN -# - -task :svn_release do - sh %{svn cp -m 'Release #{PKG_VERSION}' . #{PKG_SVN_ROOT}/release/#{PKG_VERSION}} -end - -# task :test => :update_version - # Misc Tasks --------------------------------------------------------- def egrep(pattern) Dir['**/*.rb'].each do |fn| count = 0 open(fn) do |f| while line = f.gets - count += 1 - if line =~ pattern - puts "#{fn}:#{count}:#{line}" - end + count += 1 + if line =~ pattern + puts "#{fn}:#{count}:#{line}" + end end end end end desc "Look for TODO and FIXME tags in the code" task :todo do egrep /#.*(FIXME|TODO|TBD)/ end desc "Look for Debugging print lines" task :dbg do egrep /\bDBG|\bbreakpoint\b/ end desc "List all ruby files" task :rubyfiles do puts Dir['**/*.rb'].reject { |fn| fn =~ /^pkg/ } puts Dir['bin/*'].reject { |fn| fn =~ /CVS|.svn|(~$)|(\.rb$)/ } end task :make_manifest do open("Manifest.txt", "w") do |f| f.puts Dir['**/*'].reject { |fn| fn == 'email.txt' || ! test(?f, fn) || fn =~ /CVS|.svn|([#~]$)|(.gem$)|(^pkg\/)|(^doc\/)/ }.sort.join("\n") + "\n" end end - - diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 86d9664..c6b71ac 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,27 +1,25 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'spec' require File.dirname(__FILE__) + '/../lib/currency' require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/test' -# require 'currency/exchange/rate/source/test' - def setup rate_source ||= get_rate_source Currency::Exchange::Rate::Source.default = rate_source # Force non-historical money values. Currency::Money.default_time = nil end def get_rate_source source = Currency::Exchange::Rate::Source::Test.instance Currency::Exchange::Rate::Deriver.new(:source => source) end Spec::Runner.configure do |config| config.before(:all) {setup} end
acvwilson/currency
9e9b5da1e588703bea335a4726f25b0e9d2658df
CHANGED: specs run off dev files (not the installed gem) CHANGED: Currency::Exchange cannot be used standalone
diff --git a/lib/currency/exchange.rb b/lib/currency/exchange.rb index 03550bf..6cec571 100644 --- a/lib/currency/exchange.rb +++ b/lib/currency/exchange.rb @@ -1,50 +1,48 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. -require 'currency' - # The Currency::Exchange package is responsible for # the buying and selling of currencies. # # This feature is currently unimplemented. # # Exchange rate sources are configured via Currency::Exchange::Rate::Source. # module Currency::Exchange @@default = nil @@current = nil # Returns the default Currency::Exchange object. # # If one is not specfied an instance of Currency::Exchange::Base is # created. Currency::Exchange::Base cannot service any # conversion rate requests. def self.default @@default ||= raise :Currency::Exception::Unimplemented, :default end # Sets the default Currency::Exchange object. def self.default=(x) @@default = x end # Returns the current Currency::Exchange object used during # explicit and implicit Money trading. # # If #current= has not been called and #default= has not been called, # then UndefinedExchange is raised. def self.current @@current || self.default || (raise ::Currency::Exception::UndefinedExchange, "Currency::Exchange.current not defined") end # Sets the current Currency::Exchange object used during # explicit and implicit Money conversions. def self.current=(x) @@current = x end end # module require 'currency/exchange/rate' require 'currency/exchange/rate/source' diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f863a69..86d9664 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,25 +1,27 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'spec' -require 'currency' -require 'currency/exchange/rate/source/test' +require File.dirname(__FILE__) + '/../lib/currency' +require File.dirname(__FILE__) + '/../lib/currency/exchange/rate/source/test' + +# require 'currency/exchange/rate/source/test' def setup rate_source ||= get_rate_source Currency::Exchange::Rate::Source.default = rate_source # Force non-historical money values. Currency::Money.default_time = nil end def get_rate_source source = Currency::Exchange::Rate::Source::Test.instance Currency::Exchange::Rate::Deriver.new(:source => source) end Spec::Runner.configure do |config| config.before(:all) {setup} end
acvwilson/currency
8e9c142490869960ad20c8ae9927b210b50c2e1a
Changed: gemspec
diff --git a/currency.gemspec b/currency.gemspec index e8de106..f92d4bd 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,18 +1,18 @@ Gem::Specification.new do |s| - s.name = %q{acvwilson-currency} + s.name = %q{currency} s.version = "0.5.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] s.date = %q{2008-11-14} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/currency_version.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_base_spec.rb", "spec/ar_column_spec.rb", "spec/ar_core_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.0} - s.summary = %q{acvwilson-currency 0.5.0} + s.summary = %q{currency 0.5.0} end \ No newline at end of file
acvwilson/currency
1aa938781a33933a7706ad73b920ca824ebfc6a1
Changed: gemspec
diff --git a/currency.gemspec b/currency.gemspec index 5fbe406..e8de106 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,19 +1,18 @@ Gem::Specification.new do |s| - s.name = %q{currency} + s.name = %q{acvwilson-currency} s.version = "0.5.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] s.date = %q{2008-11-14} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] - s.extra_rdoc_files = ['ChangeLog', *Dir.glob(File.join(File.dirname(__FILE__), '*.txt')).map {|f| f[2..-1]}] - s.files = [*Dir.glob(File.join(File.dirname(__FILE__), '**/*.*')).map {|f| f[2..-1]}] + s.extra_rdoc_files = ["ChangeLog", "COPYING.txt", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "TODO.txt"] + s.files = ["COPYING.txt", "currency.gemspec", "examples/ex1.rb", "examples/xe1.rb", "lib/currency/active_record.rb", "lib/currency/config.rb", "lib/currency/core_extensions.rb", "lib/currency/currency/factory.rb", "lib/currency/currency.rb", "lib/currency/currency_version.rb", "lib/currency/exception.rb", "lib/currency/exchange/rate/deriver.rb", "lib/currency/exchange/rate/source/base.rb", "lib/currency/exchange/rate/source/failover.rb", "lib/currency/exchange/rate/source/federal_reserve.rb", "lib/currency/exchange/rate/source/historical/rate.rb", "lib/currency/exchange/rate/source/historical/rate_loader.rb", "lib/currency/exchange/rate/source/historical/writer.rb", "lib/currency/exchange/rate/source/historical.rb", "lib/currency/exchange/rate/source/new_york_fed.rb", "lib/currency/exchange/rate/source/provider.rb", "lib/currency/exchange/rate/source/test.rb", "lib/currency/exchange/rate/source/the_financials.rb", "lib/currency/exchange/rate/source/timed_cache.rb", "lib/currency/exchange/rate/source/xe.rb", "lib/currency/exchange/rate/source.rb", "lib/currency/exchange/rate.rb", "lib/currency/exchange/time_quantitizer.rb", "lib/currency/exchange.rb", "lib/currency/formatter.rb", "lib/currency/macro.rb", "lib/currency/money.rb", "lib/currency/money_helper.rb", "lib/currency/parser.rb", "lib/currency.rb", "LICENSE.txt", "Manifest.txt", "README.txt", "Releases.txt", "spec/ar_base_spec.rb", "spec/ar_column_spec.rb", "spec/ar_core_spec.rb", "spec/ar_simple_spec.rb", "spec/config_spec.rb", "spec/federal_reserve_spec.rb", "spec/formatter_spec.rb", "spec/historical_writer_spec.rb", "spec/macro_spec.rb", "spec/money_spec.rb", "spec/new_york_fed_spec.rb", "spec/parser_spec.rb", "spec/spec_helper.rb", "spec/time_quantitizer_spec.rb", "spec/timed_cache_spec.rb", "spec/xe_spec.rb", "TODO.txt"] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] - s.rubyforge_project = %q{currency} - s.rubygems_version = %q{0.4.11} - s.summary = %q{currency 0.5.0} + s.rubygems_version = %q{1.3.0} + s.summary = %q{acvwilson-currency 0.5.0} end \ No newline at end of file
acvwilson/currency
0f535eb47f4b2017d128fdfe2bd99a55cc3b58aa
Fixed: gemspec
diff --git a/currency.gemspec b/currency.gemspec index 7c69974..5fbe406 100644 --- a/currency.gemspec +++ b/currency.gemspec @@ -1,19 +1,19 @@ Gem::Specification.new do |s| s.name = %q{currency} s.version = "0.5.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Asa Wilson"] s.date = %q{2008-11-14} s.description = %q{Currency conversions for Ruby} s.email = ["[email protected]"] s.extra_rdoc_files = ['ChangeLog', *Dir.glob(File.join(File.dirname(__FILE__), '*.txt')).map {|f| f[2..-1]}] - s.files = [Dir.glob(File.join(File.dirname(__FILE__), '**/*.*')).map {|f| f[2..-1]}] + s.files = [*Dir.glob(File.join(File.dirname(__FILE__), '**/*.*')).map {|f| f[2..-1]}] s.has_rdoc = true s.homepage = %q{http://currency.rubyforge.org/} s.rdoc_options = ["--main", "README.txt"] s.require_paths = ["lib"] s.rubyforge_project = %q{currency} s.rubygems_version = %q{0.4.11} s.summary = %q{currency 0.5.0} end \ No newline at end of file
acvwilson/currency
f0201663af2173021893efa1f9f402f1e54696c0
Added: gemspec for github gem creation
diff --git a/currency.gemspec b/currency.gemspec new file mode 100644 index 0000000..7c69974 --- /dev/null +++ b/currency.gemspec @@ -0,0 +1,19 @@ +Gem::Specification.new do |s| + s.name = %q{currency} + s.version = "0.5.0" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["Asa Wilson"] + s.date = %q{2008-11-14} + s.description = %q{Currency conversions for Ruby} + s.email = ["[email protected]"] + s.extra_rdoc_files = ['ChangeLog', *Dir.glob(File.join(File.dirname(__FILE__), '*.txt')).map {|f| f[2..-1]}] + s.files = [Dir.glob(File.join(File.dirname(__FILE__), '**/*.*')).map {|f| f[2..-1]}] + s.has_rdoc = true + s.homepage = %q{http://currency.rubyforge.org/} + s.rdoc_options = ["--main", "README.txt"] + s.require_paths = ["lib"] + s.rubyforge_project = %q{currency} + s.rubygems_version = %q{0.4.11} + s.summary = %q{currency 0.5.0} +end \ No newline at end of file
acvwilson/currency
b3b7370e2a6d229867285a7edb803f08889432b7
Changed: Increased precision to 6 decimal places
diff --git a/lib/currency/currency.rb b/lib/currency/currency.rb index fed1233..58dd2bf 100644 --- a/lib/currency/currency.rb +++ b/lib/currency/currency.rb @@ -1,175 +1,175 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # Represents a currency. # # Currency objects are created on-demand by Currency::Currency::Factory. # # See Currency.get method. # class Currency::Currency # Returns the ISO three-letter currency code as a symbol. # e.g. :USD, :CAD, etc. attr_reader :code # The Currency's scale factor. # e.g: the :USD scale factor is 100. attr_reader :scale # The Currency's scale factor. # e.g: the :USD scale factor is 2, where 10 ^ 2 == 100. attr_reader :scale_exp # Used by Formatter. attr_reader :format_right # Used by Formatter. attr_reader :format_left # The Currency's symbol. # e.g: USD symbol is '$' attr_accessor :symbol # The Currency's symbol as HTML. # e.g: EUR symbol is '&#8364;' (:html &#8364; :) or '&euro;' (:html &euro; :) attr_accessor :symbol_html # The default Formatter. attr_accessor :formatter # The default parser. attr_accessor :parser # Create a new currency. # This should only be called from Currency::Currency::Factory. - def initialize(code, symbol = nil, scale = 10000) + def initialize(code, symbol = nil, scale = 1000000) self.code = code self.symbol = symbol self.scale = scale @formatter = @parser = nil end # Returns the Currency object from the default Currency::Currency::Factory # by its three-letter uppercase Symbol, such as :USD, or :CAD. def self.get(code) # $stderr.puts "#{self}.get(#{code.inspect})" return nil unless code return code if code.kind_of?(::Currency::Currency) Factory.default.get_by_code(code) end # Internal method for converting currency codes to internal # Symbol format. def self.cast_code(x) x = x.upcase.intern if x.kind_of?(String) raise ::Currency::Exception::InvalidCurrencyCode, x unless x.kind_of?(Symbol) raise ::Currency::Exception::InvalidCurrencyCode, x unless x.to_s.length == 3 x end # Returns the hash of the Currency's code. def hash @code.hash end # Returns true if the Currency's are equal. def eql?(x) self.class == x.class && @code == x.code end # Returns true if the Currency's are equal. def ==(x) self.class == x.class && @code == x.code end # Clients should never call this directly. def code=(x) x = self.class.cast_code(x) unless x.nil? @code = x #$stderr.puts "#{self}.code = #{@code}"; x end # Clients should never call this directly. def scale=(x) @scale = x return x if x.nil? @scale_exp = Integer(Math.log10(@scale)); @format_right = - @scale_exp @format_left = @format_right - 1 x end # Parse a Money string in this Currency. # # See Currency::Parser#parse. # def parse(str, *opt) parser_or_default.parse(str, *opt) end def parser_or_default (@parser || ::Currency::Parser.default) end # Formats the Money value as a string using the current Formatter. # See Currency::Formatter#format. def format(m, *opt) formatter_or_default.format(m, *opt) end def formatter_or_default (@formatter || ::Currency::Formatter.default) end # Returns the Currency code as a String. def to_s @code.to_s end # Returns the default Factory's currency. def self.default Factory.default.currency end # Sets the default Factory's currency. def self.default=(x) x = self.get(x) unless x.kind_of?(self) Factory.default.currency = x end # If selector is [A-Z][A-Z][A-Z], load the currency via Factory.default. # # Currency::Currency.USD # => #<Currency::Currency:0xb7d0917c @formatter=nil, @scale_exp=2, @scale=100, @symbol="$", @format_left=-3, @code=:USD, @parser=nil, @format_right=-2> # def self.method_missing(sel, *args, &blk) if args.size == 0 && (! block_given?) && /^[A-Z][A-Z][A-Z]$/.match(sel.to_s) Factory.default.get_by_code(sel) else super end end end # class diff --git a/lib/currency/currency/factory.rb b/lib/currency/currency/factory.rb index 3215d1f..ede1cd1 100644 --- a/lib/currency/currency/factory.rb +++ b/lib/currency/currency/factory.rb @@ -1,121 +1,121 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # Responsible for creating Currency::Currency objects on-demand. class Currency::Currency::Factory @@default = nil # Returns the default Currency::Factory. def self.default @@default ||= self.new end # Sets the default Currency::Factory. def self.default=(x) @@default = x end def initialize(*opts) @currency_by_code = { } @currency_by_symbol = { } @currency = nil end # Lookup Currency by code. def get_by_code(x) x = ::Currency::Currency.cast_code(x) # $stderr.puts "get_by_code(#{x})" @currency_by_code[x] ||= install(load(::Currency::Currency.new(x))) end # Lookup Currency by symbol. def get_by_symbol(symbol) @currency_by_symbol[symbol] ||= install(load(::Currency::Currency.new(nil, symbol))) end # This method initializes a Currency object as # requested from #get_by_code or #get_by_symbol. # # This method must initialize: # # currency.code # currency.scale # # Optionally: # # currency.symbol # currency.symbol_html # # Subclasses that provide Currency metadata should override this method. # For example, loading Currency metadata from a database or YAML file. def load(currency) # $stderr.puts "BEFORE: load(#{currency.code})" # Basic if currency.code == :USD || currency.symbol == '$' # $stderr.puts "load('USD')" currency.code = :USD currency.symbol = '$' - currency.scale = 10000 + currency.scale = 1000000 elsif currency.code == :CAD # $stderr.puts "load('CAD')" currency.symbol = '$' - currency.scale = 10000 + currency.scale = 1000000 elsif currency.code == :EUR # $stderr.puts "load('CAD')" currency.symbol = nil currency.symbol_html = '&#8364;' - currency.scale = 10000 + currency.scale = 1000000 else currency.symbol = nil - currency.scale = 10000 + currency.scale = 1000000 end # $stderr.puts "AFTER: load(#{currency.inspect})" currency end # Installs a new Currency for #get_by_symbol and #get_by_code. def install(currency) raise ::Currency::Exception::UnknownCurrency unless currency @currency_by_symbol[currency.symbol] ||= currency unless currency.symbol.nil? @currency_by_code[currency.code] = currency end # Returns the default Currency. # Defaults to self.get_by_code(:USD). def currency @currency ||= self.get_by_code(:USD) end # Sets the default Currency. def currency=(x) @currency = x end # If selector is [A-Z][A-Z][A-Z], load the currency. # # factory.USD # => #<Currency::Currency:0xb7d0917c @formatter=nil, @scale_exp=2, @scale=100, @symbol="$", @format_left=-3, @code=:USD, @parser=nil, @format_right=-2> # def method_missing(sel, *args, &blk) if args.size == 0 && (! block_given?) && /^[A-Z][A-Z][A-Z]$/.match(sel.to_s) self.get_by_code(sel) else super end end end # class diff --git a/spec/config_spec.rb b/spec/config_spec.rb index cdad95a..0b910ce 100644 --- a/spec/config_spec.rb +++ b/spec/config_spec.rb @@ -1,23 +1,29 @@ require File.dirname(__FILE__) + '/spec_helper' describe Currency::Config do - it "config" do - m = Currency::Money.new(1.999) - m.should be_kind_of(Currency::Money) - m.rep.should == 19990 - + it "should truncate" do + Currency::Config.configure do | c | + c.float_ref_filter = Proc.new { | x | x } + + m = Currency::Money.new(1.999999999) + m.should be_kind_of(Currency::Money) + m.rep.should == 1999999 + end + end + + it "should round" do Currency::Config.configure do | c | c.float_ref_filter = Proc.new { | x | x.round } m = Currency::Money.new(1.99999999) m.should be_kind_of(Currency::Money) - m.rep.should == 20000 + m.rep.should == 2000000 end end end # class diff --git a/spec/formatter_spec.rb b/spec/formatter_spec.rb index 3c38fe8..f4fd46e 100644 --- a/spec/formatter_spec.rb +++ b/spec/formatter_spec.rb @@ -1,72 +1,72 @@ require File.dirname(__FILE__) + '/spec_helper' describe Currency::Formatter do before(:each) do @time = nil - @money = Currency::Money.new_rep(12345678900, :USD, @time) + @money = Currency::Money.new_rep(1234567890000, :USD, @time) end it "can convert to string" do @money.should be_kind_of(Currency::Money) @money.currency.should == Currency::Currency.default @money.currency.code.should == :USD - @money.to_s.should == "$1,234,567.8900" + @money.to_s.should == "$1,234,567.890000" @money.time.should == @time end it "handles thousands options" do - @money.to_s(:thousands => false).should == "$1234567.8900" - @money.to_s(:thousands => true).should == "$1,234,567.8900" + @money.to_s(:thousands => false).should == "$1234567.890000" + @money.to_s(:thousands => true).should == "$1,234,567.890000" end it "handles cents options" do @money.to_s(:cents => false).should == "$1,234,567" - @money.to_s(:cents => true).should == "$1,234,567.8900" + @money.to_s(:cents => true).should == "$1,234,567.890000" end it "handles symbol options" do - @money.to_s(:symbol => false).should == "1,234,567.8900" - @money.to_s(:symbol => true).should == "$1,234,567.8900" + @money.to_s(:symbol => false).should == "1,234,567.890000" + @money.to_s(:symbol => true).should == "$1,234,567.890000" end it "handles code options" do - @money.to_s(:code => false).should == "$1,234,567.8900" - @money.to_s(:code => true).should == "USD $1,234,567.8900" + @money.to_s(:code => false).should == "$1,234,567.890000" + @money.to_s(:code => true).should == "USD $1,234,567.890000" end it "handles html and more" do m = ::Currency::Money(12.45, :USD) money_string = m.to_s(:html => true, :code => true) - money_string.should == "<span class=\"currency_code\">USD</span> $12.4500" + money_string.should == "<span class=\"currency_code\">USD</span> $12.450000" m = ::Currency::Money(12.45, :EUR) money_string = m.to_s(:html => true, :code => true) - money_string.should == "<span class=\"currency_code\">EUR</span> &#8364;12.4500" + money_string.should == "<span class=\"currency_code\">EUR</span> &#8364;12.450000" m = ::Currency::Money(12345.45, :EUR) money_string = m.to_s(:html => true, :code => true, :thousands_separator => '_') - money_string.should == "<span class=\"currency_code\">EUR</span> &#8364;12_345.4500" + money_string.should == "<span class=\"currency_code\">EUR</span> &#8364;12_345.450000" end it "handles time options" do time = Time.new - m = Currency::Money.new_rep(12345678900, :USD, time) - m.to_s(:time => false).should == "$1,234,567.8900" - m.to_s(:time => true).should == "$1,234,567.8900 #{time.getutc.xmlschema(4)}" + m = Currency::Money.new_rep(1234567890000, :USD, time) + m.to_s(:time => false).should == "$1,234,567.890000" + m.to_s(:time => true).should == "$1,234,567.890000 #{time.getutc.xmlschema(4)}" end it "handles decimal options" do - @money = Currency::Money.new_rep(12345678900, :USD, @time) + @money = Currency::Money.new_rep(1234567890000, :USD, @time) @money.to_s(:decimals => 2).should == "$1,234,567.89" @money.to_s(:decimals => 3).should == "$1,234,567.890" @money.to_s(:decimals => 4).should == "$1,234,567.8900" end end diff --git a/spec/money_spec.rb b/spec/money_spec.rb index fda1f2a..0e44ef3 100644 --- a/spec/money_spec.rb +++ b/spec/money_spec.rb @@ -1,347 +1,347 @@ require File.dirname(__FILE__) + '/spec_helper' describe Currency::Money do it "create" do m = Currency::Money.new(1.99) m.should be_kind_of(Currency::Money) Currency::Currency.default.should == m.currency :USD.should == m.currency.code end describe "object money method" do it "works with a float" do m = 1.99.money(:USD) m.should be_kind_of(Currency::Money) :USD.should == m.currency.code - 19900.should == m.rep + m.rep.should == 1990000 end it "works with a FixNum" do m = 199.money(:CAD) m.should be_kind_of(Currency::Money) :CAD.should == m.currency.code - 1990000.should == m.rep + m.rep.should == 199000000 end it "works with a string" do m = "13.98".money(:CAD) m.should be_kind_of(Currency::Money) :CAD.should == m.currency.code - 139800.should == m.rep + m.rep.should == 13980000 end it "works with a string again" do m = "45.99".money(:EUR) m.should be_kind_of(Currency::Money) :EUR.should == m.currency.code - 459900.should == m.rep + m.rep.should == 45990000 end end def zero_money @zero_money ||= Currency::Money.new(0) end it "zero" do zero_money.negative?.should_not == true zero_money.zero?.should_not == nil zero_money.positive?.should_not == true end def negative_money @negative_money ||= Currency::Money.new(-1.00, :USD) end it "negative" do negative_money.negative?.should_not == nil negative_money.zero?.should_not == true negative_money.positive?.should_not == true end def positive_money @positive_money ||= Currency::Money.new(2.99, :USD) end it "positive" do positive_money.negative?.should_not == true positive_money.zero?.should_not == true positive_money.positive?.should_not == nil end it "relational" do n = negative_money z = zero_money p = positive_money (n.should < p) (n > p).should_not == true (p < n).should_not == true (p.should > n) (p != n).should_not == nil (z.should <= z) (z.should >= z) (z.should <= p) (n.should <= z) (z.should >= n) n.should == n p.should == p z.should == zero_money end it "compare" do n = negative_money z = zero_money p = positive_money (n <=> p).should == -1 (p <=> n).should == 1 (p <=> z).should == 1 (n <=> n).should == 0 (z <=> z).should == 0 (p <=> p).should == 0 end it "rep" do m = Currency::Money.new(123, :USD) m.should_not == nil - m.rep.should == 1230000 + m.rep.should == 123000000 m = Currency::Money.new(123.45, :USD) m.should_not == nil - m.rep.should == 1234500 + m.rep.should == 123450000 m = Currency::Money.new("123.456", :USD) m.should_not == nil - m.rep.should == 1234560 + m.rep.should == 123456000 end it "convert" do m = Currency::Money.new("123.456", :USD) m.should_not == nil - m.rep.should == 1234560 + m.rep.should == 123456000 m.to_i.should == 123 m.to_f.should == 123.456 - m.to_s.should == "$123.4560" + m.to_s.should == "$123.456000" end it "eql" do usd1 = Currency::Money.new(123, :USD) usd1.should_not == nil usd2 = Currency::Money.new("123", :USD) usd2.should_not == nil usd1.currency.code.should == :USD usd2.currency.code.should == :USD usd2.rep.should == usd1.rep usd1.should == usd2 end it "not eql" do usd1 = Currency::Money.new(123, :USD) usd1.should_not == nil usd2 = Currency::Money.new("123.01", :USD) usd2.should_not == nil usd1.currency.code.should == :USD usd2.currency.code.should == :USD usd2.rep.should_not == usd1.rep (usd1 != usd2).should_not == nil ################ # currency != # rep == usd = Currency::Money.new(123, :USD) usd.should_not == nil cad = Currency::Money.new(123, :CAD) cad.should_not == nil usd.currency.code.should == :USD cad.currency.code.should == :CAD cad.rep.should == usd.rep (usd.currency != cad.currency).should_not == nil (usd != cad).should_not == nil end describe "operations" do before(:each) do @usd = Currency::Money.new(123.45, :USD) @cad = Currency::Money.new(123.45, :CAD) end it "should work" do @usd.should_not == nil @cad.should_not == nil end it "handle negative money" do # - Currency::Money => Currency::Money - (- @usd).rep.should == -1234500 + (- @usd).rep.should == -123450000 (- @usd).currency.code.should == :USD - (- @cad).rep.should == -1234500 + (- @cad).rep.should == -123450000 (- @cad).currency.code.should == :CAD end it "should add monies of the same currency" do m = (@usd + @usd) m.should be_kind_of(Currency::Money) - m.rep.should == 2469000 + m.rep.should == 246900000 m.currency.code.should == :USD end it "should add monies of different currencies and return USD" do m = (@usd + @cad) m.should be_kind_of(Currency::Money) - m.rep.should == 2288907 + m.rep.should == 228890724 m.currency.code.should == :USD end it "should add monies of different currencies and return CAD" do m = (@cad + @usd) m.should be_kind_of(Currency::Money) - m.rep.should == 2679852 + m.rep.should == 267985260 m.currency.code.should == :CAD end it "should subtract monies of the same currency" do m = (@usd - @usd) m.should be_kind_of(Currency::Money) m.rep.should == 0 m.currency.code.should == :USD end it "should subtract monies of different currencies and return USD" do m = (@usd - @cad) m.should be_kind_of(Currency::Money) - m.rep.should == 180093 + m.rep.should == 18009276 m.currency.code.should == :USD end it "should subtract monies of different currencies and return CAD" do m = (@cad - @usd) m.should be_kind_of(Currency::Money) - m.rep.should == -210852 + m.rep.should == -21085260 m.currency.code.should == :CAD end it "should multiply by numerics and return money" do m = (@usd * 0.5) m.should be_kind_of(Currency::Money) - m.rep.should == 617250 + m.rep.should == 61725000 m.currency.code.should == :USD end it "should divide by numerics and return money" do m = @usd / 3 m.should be_kind_of(Currency::Money) - m.rep.should == 411500 + m.rep.should == 41150000 m.currency.code.should == :USD end it "should divide by monies of the same currency and return numeric" do m = @usd / Currency::Money.new("41.15", :USD) m.should be_kind_of(Numeric) m.should be_close(3.0, 1.0e-8) end it "should divide by monies of different currencies and return numeric" do m = (@usd / @cad) m.should be_kind_of(Numeric) m.should be_close(Currency::Exchange::Rate::Source::Test.USD_CAD, 0.0001) end end it "pivot conversions" do # Using default get_rate cad = Currency::Money.new(123.45, :CAD) cad.should_not == nil eur = cad.convert(:EUR) eur.should_not == nil m = (eur.to_f / cad.to_f) m.should be_kind_of(Numeric) m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_CAD) * Currency::Exchange::Rate::Source::Test.USD_EUR m.should be_close(m_expected, 0.001) gbp = Currency::Money.new(123.45, :GBP) gbp.should_not == nil eur = gbp.convert(:EUR) eur.should_not == nil m = (eur.to_f / gbp.to_f) m.should be_kind_of(Numeric) m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_GBP) * Currency::Exchange::Rate::Source::Test.USD_EUR m.should be_close(m_expected, 0.001) end it "invalid currency code" do lambda {Currency::Money.new(123, :asdf)}.should raise_error(Currency::Exception::InvalidCurrencyCode) lambda {Currency::Money.new(123, 5)}.should raise_error(Currency::Exception::InvalidCurrencyCode) end it "time default" do Currency::Money.default_time = nil usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should == nil Currency::Money.default_time = Time.now usd = Currency::Money.new(123.45, :USD) usd.should_not == nil Currency::Money.default_time.should == usd.time end it "time now" do Currency::Money.default_time = :now usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should_not == nil sleep 1 usd2 = Currency::Money.new(123.45, :USD) usd2.should_not == nil usd2.time.should_not == nil (usd.time != usd2.time).should_not == nil Currency::Money.default_time = nil end it "time fixed" do Currency::Money.default_time = Time.new usd = Currency::Money.new(123.45, :USD) usd.should_not == nil usd.time.should_not == nil sleep 1 usd2 = Currency::Money.new(123.45, :USD) usd2.should_not == nil usd2.time.should_not == nil usd.time.should == usd2.time end end diff --git a/spec/time_quantitizer_spec.rb b/spec/time_quantitizer_spec.rb index 6fc70fc..1db2711 100644 --- a/spec/time_quantitizer_spec.rb +++ b/spec/time_quantitizer_spec.rb @@ -1,136 +1,115 @@ -# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> -# See LICENSE.txt for details. +require File.dirname(__FILE__) + '/spec_helper' -#require File.dirname(__FILE__) + '/../test_helper' +describe Currency::Exchange::TimeQuantitizerTest do -require 'test/test_base' -require 'currency/exchange/time_quantitizer' + def assert_test_day(t0) + tq = test_create -module Currency -module Exchange + begin + t1 = tq.quantitize_time(t0).should_not == nil + #$stderr.puts "t0 = #{t0}" + #$stderr.puts "t1 = #{t1}" + + t1.year.should == t0.year + t1.month.should == t0.month + t1.day.should == t0.day + assert_time_beginning_of_day(t1) + rescue Object => err + raise("#{err}\nDuring quantitize_time(#{t0} (#{t0.to_i}))") + end -class TimeQuantitizerTest < TestBase - before do - super + t1 end + + def assert_test_minute(t0) + tq = TimeQuantitizer.new(:time_quant_size => 60) # 1 minute + + tq.local_timezone_offset + + t1 = tq.quantitize_time(t0).should_not == nil + $stderr.puts "t0 = #{t0}" + $stderr.puts "t1 = #{t1}" - ############################################ - # - # + t1.year.should == t0.year + t1.month.should == t0.month + t1.day.should == t0.day + assert_time_beginning_of_day(t1) + + t1 + end + + + def assert_time_beginning_of_day(t1) + t1.hour.should == 0 + assert_time_beginning_of_hour(t1) + end + + + def assert_time_beginning_of_hour(t1) + t1.min.should == 0 + assert_time_beginning_of_min(t1) + end + + + def assert_time_beginning_of_min(t1) + t1.sec.should == 0 + endshould_not it "create" do - assert_kind_of TimeQuantitizer, tq = TimeQuantitizer.new() + tq = TimeQuantitizer.new() + tg.should be_kind_of(TimeQuantitizer) tq.time_quant_size.should == 60 * 60 * 24 tq.quantitize_time(nil).should == nil - - tq end it "localtime" do t1 = assert_test_day(t0 = Time.new) t1.utc_offset.should == t0.utc_offset t1.utc_offset.should == Time.now.utc_offset end it "utc" do t1 = assert_test_day(t0 = Time.new.utc) t1.utc_offset.should == t0.utc_offset end it "random" do (1 .. 1000).each do t0 = Time.at(rand(1234567901).to_i) assert_test_day(t0) assert_test_hour(t0) # Problem year? t0 = Time.parse('1977/01/01') + rand(60 * 60 * 24 * 7 * 52).to_i assert_test_day(t0) assert_test_hour(t0) # Problem year? t0 = Time.parse('1995/01/01') + rand(60 * 60 * 24 * 7 * 52).to_i assert_test_day(t0) assert_test_hour(t0) end end - def assert_test_day(t0) - tq = test_create - - begin - t1 = tq.quantitize_time(t0).should.not == nil - #$stderr.puts "t0 = #{t0}" - #$stderr.puts "t1 = #{t1}" - - t1.year.should == t0.year - t1.month.should == t0.month - t1.day.should == t0.day - assert_time_beginning_of_day(t1) - rescue Object => err - raise("#{err}\nDuring quantitize_time(#{t0} (#{t0.to_i}))") - end - - t1 - end - - def assert_test_hour(t0) tq = TimeQuantitizer.new(:time_quant_size => 60 * 60) # 1 hour - t1 = tq.quantitize_time(t0).should.not == nil + t1 = tq.quantitize_time(t0).should_not == nil #$stderr.puts "t0 = #{t0}" #$stderr.puts "t1 = #{t1}" t1.year.should == t0.year t1.month.should == t0.month t1.day.should == t0.day assert_time_beginning_of_hour(t1) t1 end - - def assert_test_minute(t0) - tq = TimeQuantitizer.new(:time_quant_size => 60) # 1 minute - - tq.local_timezone_offset - - t1 = tq.quantitize_time(t0).should.not == nil - $stderr.puts "t0 = #{t0}" - $stderr.puts "t1 = #{t1}" - - t1.year.should == t0.year - t1.month.should == t0.month - t1.day.should == t0.day - assert_time_beginning_of_day(t1) - - t1 - end - - - def assert_time_beginning_of_day(t1) - t1.hour.should == 0 - assert_time_beginning_of_hour(t1) - end - - - def assert_time_beginning_of_hour(t1) - t1.min.should == 0 - assert_time_beginning_of_min(t1) - end - - - def assert_time_beginning_of_min(t1) - t1.sec.should == 0 - end - end # class -end # module -end # module
acvwilson/currency
fce7b767af5dc84a19644e98d0b4d6c38af3fe8d
Changed: tests to specs using spec_converter, got some specs running/passing in rspec
diff --git a/lib/currency/core_extensions.rb b/lib/currency/core_extensions.rb index 3b42015..4a2b40f 100644 --- a/lib/currency/core_extensions.rb +++ b/lib/currency/core_extensions.rb @@ -1,41 +1,48 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. class Object # Exact conversion to Money representation value. def money(*opts) Currency::Money(self, *opts) end end class Integer # Exact conversion to Money representation value. def Money_rep(currency, time = nil) Integer(self * currency.scale) end end class Float # Inexact conversion to Money representation value. def Money_rep(currency, time = nil) Integer(Currency::Config.current.float_ref_filter.call(self * currency.scale)) end + + def round_with_precision(precision = nil) + precision.nil? ? round_without_precision : (self * (10 ** precision)).round_without_precision / (10 ** precision).to_f + end + alias_method :round_without_precision, :round + alias_method :round, :round_with_precision end + class String # Exact conversion to Money representation value. def Money_rep(currency, time = nil) x = currency.parse(self, :currency => currency, :time => time) x = x.rep if x.respond_to?(:rep) x end end diff --git a/lib/currency/formatter.rb b/lib/currency/formatter.rb index 50bf54f..77cdaff 100644 --- a/lib/currency/formatter.rb +++ b/lib/currency/formatter.rb @@ -1,300 +1,300 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'rss/rss' # Time#xmlschema # This class formats a Money value as a String. # Each Currency has a default Formatter. class Currency::Formatter # The underlying object for Currency::Formatter#format. # This object is cloned and initialized with strings created # from Formatter#format. # It handles the Formatter#format string interpolation. class Template @@empty_hash = { } @@empty_hash.freeze # The template string. attr_accessor :template # The Currency::Money object being formatted. attr_accessor :money # The Currency::Currency object being formatted. attr_accessor :currency # The sign: '-' or nil. attr_accessor :sign # The whole part of the value, with thousands_separator or nil. attr_accessor :whole # The fraction part of the value, with decimal_separator or nil. attr_accessor :fraction # The currency symbol or nil. attr_accessor :symbol # The currency code or nil. attr_accessor :code # The time or nil. attr_accessor :time def initialize(opts = @@empty_hash) @template = @template_proc = nil opts.each_pair{ | k, v | self.send("#{k}=", v) } end # Sets the template string and uncaches the template_proc. def template=(x) if @template != x @template_proc = nil end @template = x end # Defines a the self._format template procedure using # the template as a string to be interpolated. def template_proc(template = @template) return @template_proc if @template_proc @template_proc = template || '' # @template_proc = @template_proc.gsub(/[\\"']/) { | x | "\\" + x } @template_proc = "def self._format; \"#{@template_proc}\"; end" self.instance_eval @template_proc @template_proc end # Formats the current state using the template. def format template_proc _format end end # Defaults to ',' attr_accessor :thousands_separator # Defaults to '.' attr_accessor :decimal_separator # If true, insert _thousands_separator_ between each 3 digits in the whole value. attr_accessor :thousands # If true, append _decimal_separator_ and decimal digits after whole value. attr_accessor :cents # If true, prefix value with currency symbol. attr_accessor :symbol # If true, append currency code. attr_accessor :code # If true, append the time. attr_accessor :time # The number of fractional digits in the time. # Defaults to 4. attr_accessor :time_fractional_digits # If true, use html formatting. # # Currency::Money(12.45, :EUR).to_s(:html => true; :code => true) # => "&#8364;12.45 <span class=\"currency_code\">EUR</span>" attr_accessor :html # A template string used to format a money value. # Defaults to: # # '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}#{time && " "}#{time}' attr_accessor :template # Set the decimal_places # Defaults to: nil - attr_accessor :decimal_places + attr_accessor :decimals # If passed true, formats for an input field (i.e.: as a number). def as_input_value=(x) if x self.thousands_separator = '' self.decimal_separator = '.' self.thousands = false self.cents = true self.symbol = false self.code = false self.html = false self.time = false self.time_fractional_digits = nil end x end @@default = nil # Get the default Formatter. def self.default @@default || self.new end # Set the default Formatter. def self.default=(x) @@default = x end def initialize(opt = { }) @thousands_separator = ',' @decimal_separator = '.' @thousands = true @cents = true @symbol = true @code = false @html = false @time = false @time_fractional_digits = 4 @template = '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}#{time && " "}#{time}' @template_object = nil - @decimal_places = nil + @decimals = nil opt.each_pair{ | k, v | self.send("#{k}=", v) } end def currency=(x) # :nodoc: # DO NOTHING! end # Sets the template and the Template#template. def template=(x) if @template_object @template_object.template = x end @template = x end # Returns the Template object. def template_object return @template_object if @template_object @template_object = Template.new @template_object.template = @template if @template # $stderr.puts "template.template = #{@template_object.template.inspect}" @template_object.template_proc # pre-cache before clone. @template_object end def _format(m, currency = nil, time = nil) # :nodoc: # Get currency. currency ||= m.currency # Get time. time ||= m.time # set decimal places - @decimal_places ||= currency.scale_exp + @decimals ||= currency.scale_exp # Setup template tmpl = self.template_object.clone # $stderr.puts "template.template = #{tmpl.template.inspect}" tmpl.money = m tmpl.currency = currency # Get scaled integer representation for this Currency. # $stderr.puts "m.currency = #{m.currency}, currency => #{currency}" x = m.Money_rep(currency) # Remove sign. x = - x if ( neg = x < 0 ) tmpl.sign = neg ? '-' : nil # Convert to String. x = x.to_s # Keep prefixing "0" until filled to scale. while ( x.length <= currency.scale_exp ) x = "0" + x end # Insert decimal place. whole = x[0 .. currency.format_left] fraction = x[currency.format_right .. -1] # Round the fraction to the supplied number of decimal places - fraction = ((fraction.to_f / currency.scale).round(@decimal_places) * (10 ** @decimal_places)).to_i.to_s + fraction = ((fraction.to_f / currency.scale).round(@decimals) * (10 ** @decimals)).to_i.to_s # Do thousands. x = whole if @thousands && (@thousands_separator && ! @thousands_separator.empty?) x.reverse! x.gsub!(/(\d\d\d)/) {|y| y + @thousands_separator} x.sub!(/#{@thousands_separator}$/,'') x.reverse! end # Put whole and fractional parts. tmpl.whole = x tmpl.fraction = @cents && @decimal_separator ? @decimal_separator + fraction : nil # Add symbol? tmpl.symbol = @symbol ? ((@html && currency.symbol_html) || currency.symbol) : nil # Add currency code. tmpl.code = @code ? _format_Currency(currency) : nil # Add time. tmpl.time = @time && time ? _format_Time(time) : nil # Ask template to format the components. tmpl.format end def _format_Currency(c) # :nodoc: x = '' x << '<span class="currency_code">' if @html x << c.code.to_s x << '</span>' if @html x end def _format_Time(t) # :nodoc: x = '' x << t.getutc.xmlschema(@time_fractional_digits) if t x end @@empty_hash = { } @@empty_hash.freeze # Format a Money object as a String. # # m = Money.new("1234567.89") # m.to_s(:code => true, :symbol => false) # => "1,234,567.89 USD" # def format(m, opt = @@empty_hash) fmt = self unless opt.empty? fmt = fmt.clone opt.each_pair{ | k, v | fmt.send("#{k}=", v) } end # $stderr.puts "format(opt = #{opt.inspect})" fmt._format(m, opt[:currency]) # Allow override of current currency. end end # class diff --git a/lib/currency/money.rb b/lib/currency/money.rb index c6c5952..4ec8daa 100644 --- a/lib/currency/money.rb +++ b/lib/currency/money.rb @@ -1,295 +1,296 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. # # Represents an amount of money in a particular currency. # # A Money object stores its value using a scaled Integer representation # and a Currency object. # # A Money object also has a time, which is used in conversions # against historical exchange rates. # class Currency::Money include Comparable @@default_time = nil def self.default_time @@default_time end def self.default_time=(x) @@default_time = x end @@empty_hash = { } @@empty_hash.freeze # # DO NOT CALL THIS DIRECTLY: # # See Currency.Money() function. # # Construct a Money value object # from a pre-scaled external representation: # where x is a Float, Integer, String, etc. # # If a currency is not specified, Currency.default is used. # # x.Money_rep(currency) # # is invoked to coerce x into a Money representation value. # # For example: # # 123.Money_rep(:USD) => 12300 # # Because the USD Currency object has a #scale of 100 # # See #Money_rep(currency) mixin. # def initialize(x, currency = nil, time = nil) opts ||= @@empty_hash # Set ivars. currency = ::Currency::Currency.get(currency) @currency = currency @time = time || ::Currency::Money.default_time @time = ::Currency::Money.now if @time == :now if x.kind_of?(String) if currency m = currency.parser_or_default.parse(x, :currency => currency) else m = ::Currency::Parser.default.parse(x) end @currency = m.currency unless @currency @time = m.time if m.time @rep = m.rep else @currency = ::Currency::Currency.default unless @currency @rep = x.Money_rep(@currency) end end # Returns a Time.new # Can be modifed for special purposes. def self.now Time.new end # Compatibility with Money package. def self.us_dollar(x) self.new(x, :USD) end # Compatibility with Money package. def cents @rep end # Construct from post-scaled internal representation. def self.new_rep(r, currency = nil, time = nil) x = self.new(0, currency, time) x.set_rep(r) x end # Construct from post-scaled internal representation. # using the same currency. # # x = Currency.Money("1.98", :USD) # x.new_rep(123) => USD $1.23 # # time defaults to self.time. def new_rep(r, time = nil) time ||= @time x = self.class.new(0, @currency, time) x.set_rep(r) x end # Do not call this method directly. # CLIENTS SHOULD NEVER CALL set_rep DIRECTLY. # You have been warned in ALL CAPS. def set_rep(r) # :nodoc: r = r.to_i unless r.kind_of?(Integer) @rep = r end # Do not call this method directly. # CLIENTS SHOULD NEVER CALL set_time DIRECTLY. # You have been warned in ALL CAPS. def set_time(time) # :nodoc: @time = time end # Returns the Money representation (usually an Integer). def rep @rep end # Get the Money's Currency. def currency @currency end # Get the Money's time. def time @time end # Convert Money to another Currency. # currency can be a Symbol or a Currency object. # If currency is nil, the Currency.default is used. def convert(currency, time = nil) currency = ::Currency::Currency.default if currency.nil? currency = ::Currency::Currency.get(currency) unless currency.kind_of?(Currency) if @currency == currency self else time = self.time if time == :money ::Currency::Exchange::Rate::Source.current.convert(self, currency, time) end end # Hash for hash table: both value and currency. # See #eql? below. def hash @rep.hash ^ @currency.hash end # True if money values have the same value and currency. def eql?(x) self.class == x.class && @rep == x.rep && @currency == x.currency end # True if money values have the same value and currency. def ==(x) self.class == x.class && @rep == x.rep && @currency == x.currency end # Compares Money values. # Will convert x to self.currency before comparision. def <=>(x) if @currency == x.currency @rep <=> x.rep else @rep <=> convert(@currency, @time).rep end end # - Money => Money # # Negates a Money value. def -@ new_rep(- @rep) end # Money + (Money | Number) => Money # # Right side may be coerced to left side's Currency. def +(x) new_rep(@rep + x.Money_rep(@currency)) end # Money - (Money | Number) => Money # # Right side may be coerced to left side's Currency. def -(x) new_rep(@rep - x.Money_rep(@currency)) end # Money * Number => Money # # Right side must be Number. def *(x) new_rep(@rep * x) end # Money / Money => Float (ratio) # Money / Number => Money # # Right side must be Money or Number. # Right side Integers are not coerced to Float before # division. def /(x) if x.kind_of?(self.class) (@rep.to_f) / (x.Money_rep(@currency).to_f) else new_rep(@rep / x) end end # Formats the Money value as a String using the Currency's Formatter. def format(*opt) @currency.format(self, *opt) end # Formats the Money value as a String. def to_s(*opt) @currency.format(self, *opt) end # Coerces the Money's value to a Float. # May cause loss of precision. def to_f Float(@rep) / @currency.scale end # Coerces the Money's value to an Integer. # May cause loss of precision. def to_i @rep / @currency.scale end # True if the Money's value is zero. def zero? @rep == 0 end # True if the Money's value is greater than zero. def positive? @rep > 0 end # True if the Money's value is less than zero. def negative? @rep < 0 end # Returns the Money's value representation in another currency. def Money_rep(currency, time = nil) # Attempt conversion? if @currency != currency || (time && @time != time) - self.convert(currency, time).rep + + self.convert(currency, time).rep # raise ::Currency::Exception::Generic, "Incompatible Currency: #{@currency} != #{currency}" else @rep end end # Basic inspection, with symbol, currency code and time. # The standard #inspect method is available as #inspect_deep. def inspect(*opts) self.format(:symbol => true, :code => true, :time => true) end # How to alias a method defined in an object superclass in a different class: define_method(:inspect_deep, Object.instance_method(:inspect)) # How call a method defined in a superclass from a method with a different name: # def inspect_deep(*opts) # self.class.superclass.instance_method(:inspect).bind(self).call # end end # class diff --git a/spec/ar_base_spec.rb b/spec/ar_base_spec.rb index efbac5f..a4f1539 100644 --- a/spec/ar_base_spec.rb +++ b/spec/ar_base_spec.rb @@ -1,151 +1,140 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' require 'rubygems' require 'active_record' require 'active_record/migration' require 'currency/active_record' AR_M = ActiveRecord::Migration AR_B = ActiveRecord::Base module Currency class ArTestBase < TestBase ################################################## - def setup + before do super AR_B.establish_connection(database_spec) # Subclasses can override this. @currency_test_migration ||= nil @currency_test ||= nil # schema_down schema_up end def teardown super # schema_down end def database_spec # TODO: Get from ../config/database.yml:test # Create test database on: # MYSQL: # # sudo mysqladmin create test; # sudo mysql # grant all on test.* to test@localhost identified by 'test'; # flush privileges; # POSTGRES: # # CREATE USER test PASSWORD 'test'; # CREATE DATABASE test WITH OWNER = test; # @database_spec = { :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', :host => ENV['TEST_DB_HOST'] || 'localhost', :username => ENV['TEST_DB_USER'] || 'test', :password => ENV['TEST_DB_PASS'] || 'test', :database => ENV['TEST_DB_TEST'] || 'test' } end def schema_up return unless @currency_test_migration begin @currency_test_migration.migrate(:up) rescue Object =>e $stderr.puts "Warning: #{e}" end end def schema_down return unless @currency_test_migration begin @currency_test_migration.migrate(:down) rescue Object => e $stderr.puts "Warning: #{e}" end end ################################################## # Scaffold # def insert_records delete_records @currency_test.reset_column_information @usd = @currency_test.new(:name => '#1: USD', :amount => Money.new("12.34", :USD)) @usd.save @cad = @currency_test.new(:name => '#2: CAD', :amount => Money.new("56.78", :CAD)) @cad.save end def delete_records @currency_test.destroy_all end ################################################## def assert_equal_money(a,b) - assert_not_nil a - assert_not_nil b + a.should_not be_nil + b.should_not be_nil # Make sure a and b are not the same object. - assert_not_equal a.object_id, b.object_id - assert_equal a.id, b.id - assert_not_nil a.amount - assert_kind_of Money, a.amount - assert_not_nil b.amount - assert_kind_of Money, b.amount + b.object_id.should_not == a.object_id + b.id.should == a.id + a.amount.should.not == nil + a.amount.should be_kind_of(Money) + b.amount.should.not == nil + b.amount.should be_kind_of(Money) # Make sure that what gets stored in the database comes back out # when converted back to the original currency. - assert_equal a.amount.convert(b.amount.currency).rep, b.amount.rep + b.amount.rep.should == a.amount.convert(b.amount.currency).rep end def assert_equal_currency(a,b) assert_equal_money a, b - assert_equal a.amount.rep, b.amount.rep - assert_equal a.amount.currency, b.amount.currency - assert_equal a.amount.currency.code, b.amount.currency.code + b.amount.rep.should == a.amount.rep + b.amount.currency.should == a.amount.currency + b.amount.currency.code.should == a.amount.currency.code end - - - ################################################## - # - # - - - def test_dummy - - end - end end # module diff --git a/spec/ar_column_spec.rb b/spec/ar_column_spec.rb index bf8acb3..1be91a2 100644 --- a/spec/ar_column_spec.rb +++ b/spec/ar_column_spec.rb @@ -1,69 +1,69 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/ar_test_core' require 'currency' require 'rubygems' require 'active_record' require 'active_record/migration' require 'currency/active_record' module Currency class ArFieldTest < ArTestCore ################################################## # Basic CurrenyTest AR::B class # TABLE_NAME = 'currency_column_test' class CurrencyColumnTestMigration < AR_M def self.up create_table TABLE_NAME.intern do |t| t.column :name, :string t.column :amount, :integer # Money t.column :amount_currency, :string, :size => 3 # Money.currency.code end end def self.down drop_table TABLE_NAME.intern end end class CurrencyColumnTest < AR_B set_table_name TABLE_NAME attr_money :amount, :currency_column => true end ################################################## - def setup + before do @currency_test_migration ||= CurrencyColumnTestMigration @currency_test ||= CurrencyColumnTest super end def teardown super end ################################################## - def test_field + it "field" do insert_records - assert_not_nil usd = @currency_test.find(@usd.id) + usd = @currency_test.find(@usd.id).should.not == nil assert_equal_currency usd, @usd - assert_not_nil cad = @currency_test.find(@cad.id) + cad = @currency_test.find(@cad.id).should.not == nil assert_equal_currency cad, @cad end end end # module diff --git a/spec/ar_core_spec.rb b/spec/ar_core_spec.rb index 324cc5f..f7ee92d 100644 --- a/spec/ar_core_spec.rb +++ b/spec/ar_core_spec.rb @@ -1,64 +1,64 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/ar_test_base' module Currency class ArTestCore < ArTestBase ################################################## # Basic CurrenyTest AR::B class # TABLE_NAME = 'currency_test' class CurrencyTestMigration < AR_M def self.up create_table TABLE_NAME.intern do |t| t.column :name, :string t.column :amount, :integer # Money end end def self.down drop_table TABLE_NAME.intern end end class CurrencyTest < AR_B set_table_name TABLE_NAME attr_money :amount end ################################################## - def setup + before do @currency_test_migration ||= CurrencyTestMigration @currency_test ||= CurrencyTest super end def teardown super # schema_down end ################################################## # # - def test_insert + it "insert" do insert_records end end end # module diff --git a/spec/ar_simple_spec.rb b/spec/ar_simple_spec.rb index 148da26..09d7229 100644 --- a/spec/ar_simple_spec.rb +++ b/spec/ar_simple_spec.rb @@ -1,31 +1,31 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/ar_test_core' require 'currency' require 'rubygems' require 'active_record' require 'active_record/migration' require 'currency/active_record' module Currency class ArSimpleTest < ArTestCore - def test_simple + it "simple" do insert_records - assert_not_nil usd = @currency_test.find(@usd.id) + usd = @currency_test.find(@usd.id).should.not == nil assert_equal_currency usd, @usd - assert_not_nil cad = @currency_test.find(@cad.id) + cad = @currency_test.find(@cad.id).should.not == nil assert_equal_money cad, @cad - assert_equal cad.amount.currency.code, :USD + :USD.should == cad.amount.currency.code end end end # module diff --git a/spec/config_spec.rb b/spec/config_spec.rb index 1024747..cdad95a 100644 --- a/spec/config_spec.rb +++ b/spec/config_spec.rb @@ -1,36 +1,23 @@ -# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> -# See LICENSE.txt for details. +require File.dirname(__FILE__) + '/spec_helper' +describe Currency::Config do -require 'test/test_base' -require 'currency' + it "config" do + m = Currency::Money.new(1.999) + m.should be_kind_of(Currency::Money) + m.rep.should == 19990 -module Currency - -class ConfigTest < TestBase - def setup - super - end - - ############################################ - # Simple stuff. - # - - def test_config - assert_kind_of Money, m = Money.new(1.999) - assert_equal 199, m.rep - - Config.configure do | c | + Currency::Config.configure do | c | c.float_ref_filter = Proc.new { | x | x.round } - assert_kind_of Money, m = Money.new(1.999) - assert_equal 200, m.rep + m = Currency::Money.new(1.99999999) + m.should be_kind_of(Currency::Money) + m.rep.should == 20000 end end end # class -end # module diff --git a/spec/federal_reserve_spec.rb b/spec/federal_reserve_spec.rb index a4aa4c9..c7ec0e6 100644 --- a/spec/federal_reserve_spec.rb +++ b/spec/federal_reserve_spec.rb @@ -1,75 +1,75 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' # For :type => :money require 'currency/exchange/rate/source/federal_reserve' module Currency class FederalReserveTest < TestBase - def setup + before do super end @@available = nil # New York Fed rates are not available on Saturday and Sunday. def available? if @@available == nil @@available = @source.available? STDERR.puts "Warning: FederalReserve unavailable on Saturday and Sunday, skipping tests." unless @@available end @@available end def get_rate_source # Force FederalReserve Exchange. verbose = false source = @source = Exchange::Rate::Source::FederalReserve.new(:verbose => verbose) deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) end - def test_usd_cad + it "usd cad" do return unless available? # yesterday = Time.now.to_date - 1 - assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates + rates = Exchange::Rate::Source.default.source.raw_rates.should.not == nil #assert_not_nil rates[:USD] #assert_not_nil usd_cad = rates[:USD][:CAD] - assert_not_nil usd = Money.new(123.45, :USD) - assert_not_nil cad = usd.convert(:CAD) + usd = Money.new(123.45, :USD).should.not == nil + cad = usd.convert(:CAD).should.not == nil # assert_kind_of Numeric, m = (cad.to_f / usd.to_f) # $stderr.puts "m = #{m}" # assert_equal_float usd_cad, m, 0.001 end - def test_cad_eur + it "cad eur" do return unless available? - assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates + rates = Exchange::Rate::Source.default.source.raw_rates.should.not == nil #assert_not_nil rates[:USD] #assert_not_nil usd_cad = rates[:USD][:CAD] #assert_not_nil usd_eur = rates[:USD][:EUR] - assert_not_nil cad = Money.new(123.45, :CAD) - assert_not_nil eur = cad.convert(:EUR) + cad = Money.new(123.45, :CAD).should.not == nil + eur = cad.convert(:EUR).should.not == nil #assert_kind_of Numeric, m = (eur.to_f / cad.to_f) # $stderr.puts "m = #{m}" #assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 end end end # module diff --git a/spec/formatter_spec.rb b/spec/formatter_spec.rb index c9e2b99..3c38fe8 100644 --- a/spec/formatter_spec.rb +++ b/spec/formatter_spec.rb @@ -1,92 +1,72 @@ -# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> -# See LICENSE.txt for details. +require File.dirname(__FILE__) + '/spec_helper' -require 'test/test_base' -require 'currency' - -module Currency - -class FormatterTest < TestBase - def setup - super +describe Currency::Formatter do + before(:each) do + @time = nil + @money = Currency::Money.new_rep(12345678900, :USD, @time) + end - ############################################ - # Simple stuff. - # - - def test_default(time = nil) - assert_kind_of Money, m = ::Currency::Money.new_rep(123456789, :USD, time) - assert_equal Currency.default, m.currency - assert_equal :USD, m.currency.code - assert_equal "$1,234,567.89", m.to_s - assert_equal time, m.time - - m + it "can convert to string" do + @money.should be_kind_of(Currency::Money) + @money.currency.should == Currency::Currency.default + @money.currency.code.should == :USD + @money.to_s.should == "$1,234,567.8900" + @money.time.should == @time end - def test_thousands - m = test_default - assert_equal "$1234567.89", m.to_s(:thousands => false) - assert_equal "$1,234,567.89", m.to_s(:thousands => true) - - m + it "handles thousands options" do + @money.to_s(:thousands => false).should == "$1234567.8900" + @money.to_s(:thousands => true).should == "$1,234,567.8900" end - def test_cents - m = test_default - assert_equal "$1,234,567", m.to_s(:cents => false) - assert_equal "$1,234,567.89", m.to_s(:cents => true) - - m + it "handles cents options" do + @money.to_s(:cents => false).should == "$1,234,567" + @money.to_s(:cents => true).should == "$1,234,567.8900" end - def test_symbol - m = test_default - assert_equal "1,234,567.89", m.to_s(:symbol => false) - assert_equal "$1,234,567.89", m.to_s(:symbol => true) - - m + it "handles symbol options" do + @money.to_s(:symbol => false).should == "1,234,567.8900" + @money.to_s(:symbol => true).should == "$1,234,567.8900" end - def test_code - m = test_default - assert_equal "$1,234,567.89", m.to_s(:code => false) - assert_equal "USD $1,234,567.89", m.to_s(:code => true) - - m + it "handles code options" do + @money.to_s(:code => false).should == "$1,234,567.8900" + @money.to_s(:code => true).should == "USD $1,234,567.8900" end - def test_misc + it "handles html and more" do m = ::Currency::Money(12.45, :USD) - assert_equal "<span class=\"currency_code\">USD</span> $12.45", - m.to_s(:html => true, :code => true) + money_string = m.to_s(:html => true, :code => true) + money_string.should == "<span class=\"currency_code\">USD</span> $12.4500" + m = ::Currency::Money(12.45, :EUR) - assert_equal "<span class=\"currency_code\">EUR</span> &#8364;12.45", - m.to_s(:html => true, :code => true) + money_string = m.to_s(:html => true, :code => true) + money_string.should == "<span class=\"currency_code\">EUR</span> &#8364;12.4500" m = ::Currency::Money(12345.45, :EUR) - assert_equal "<span class=\"currency_code\">EUR</span> &#8364;12_345.45", - m.to_s(:html => true, :code => true, :thousands_separator => '_') + money_string = m.to_s(:html => true, :code => true, :thousands_separator => '_') + money_string.should == "<span class=\"currency_code\">EUR</span> &#8364;12_345.4500" end - def test_time + it "handles time options" do time = Time.new - m = test_default(time) - assert_equal "$1,234,567.89", m.to_s(:time => false) - assert_equal "$1,234,567.89 #{time.getutc.xmlschema(4)}", m.to_s(:time => true) - - m + m = Currency::Money.new_rep(12345678900, :USD, time) + m.to_s(:time => false).should == "$1,234,567.8900" + m.to_s(:time => true).should == "$1,234,567.8900 #{time.getutc.xmlschema(4)}" end + it "handles decimal options" do + @money = Currency::Money.new_rep(12345678900, :USD, @time) + @money.to_s(:decimals => 2).should == "$1,234,567.89" + @money.to_s(:decimals => 3).should == "$1,234,567.890" + @money.to_s(:decimals => 4).should == "$1,234,567.8900" + end end - -end # module - diff --git a/spec/historical_writer_spec.rb b/spec/historical_writer_spec.rb index 3ae739b..7d7d342 100644 --- a/spec/historical_writer_spec.rb +++ b/spec/historical_writer_spec.rb @@ -1,187 +1,187 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/ar_test_base' require 'rubygems' require 'active_record' require 'active_record/migration' require 'currency' # For :type => :money require 'currency/exchange/rate/source/historical' require 'currency/exchange/rate/source/historical/writer' require 'currency/exchange/rate/source/xe' require 'currency/exchange/rate/source/new_york_fed' module Currency class HistoricalWriterTest < ArTestBase RATE_CLASS = Exchange::Rate::Source::Historical::Rate TABLE_NAME = RATE_CLASS.table_name class HistoricalRateMigration < AR_M def self.up RATE_CLASS.__create_table(self) end def self.down drop_table TABLE_NAME.intern end end def initialize(*args) @currency_test_migration = HistoricalRateMigration super @src = Exchange::Rate::Source::Xe.new @src2 = Exchange::Rate::Source::NewYorkFed.new end - def setup + before do super end - def test_writer - assert_not_nil src = @src - assert_not_nil writer = Exchange::Rate::Source::Historical::Writer.new() + it "writer" do + src = @src.should.not == nil + writer = Exchange::Rate::Source::Historical::Writer.new().should.not == nil writer.time_quantitizer = :current writer.required_currencies = [ :USD, :GBP, :EUR, :CAD ] writer.base_currencies = [ :USD ] writer.preferred_currencies = writer.required_currencies writer.reciprocal_rates = true writer.all_rates = true writer.identity_rates = false writer end def writer_src writer = test_writer writer.source = @src rates = writer.write_rates - assert_not_nil rates - assert rates.size > 0 - assert 12, rates.size + rates.should.not == nil + rates.size.should > 0 + 12, rates.size.should.not == nil assert_h_rates(rates, writer) end def writer_src2 writer = test_writer writer.source = @src2 return unless writer.source.available? rates = writer.write_rates - assert_not_nil rates - assert rates.size > 0 - assert_equal 12, rates.size + rates.should.not == nil + rates.size.should > 0 + rates.size.should == 12 assert_h_rates(rates, writer) end def xxx_test_required_failure - assert_not_nil writer = Exchange::Rate::Source::Historical::Writer.new() - assert_not_nil src = @src + writer = Exchange::Rate::Source::Historical::Writer.new().should.not == nil + src = @src.should.not == nil writer.source = src writer.required_currencies = [ :USD, :GBP, :EUR, :CAD, :ZZZ ] writer.preferred_currencies = writer.required_currencies assert_raises(::RuntimeError) { writer.selected_rates } end - def test_historical_rates + it "historical rates" do # Make sure there are historical Rates avail for today. writer_src writer_src2 # Force Historical Rate Source. source = Exchange::Rate::Source::Historical.new deriver = Exchange::Rate::Deriver.new(:source => source) Exchange::Rate::Source.default = deriver - assert_not_nil rates = source.get_raw_rates - assert ! rates.empty? + rates = source.get_raw_rates.should.not == nil + rates.empty?.should.not == true # $stderr.puts "historical rates = #{rates.inspect}" - assert_not_nil rates = source.get_rates - assert ! rates.empty? + rates = source.get_rates.should.not == nil + rates.empty?.should.not == true # $stderr.puts "historical rates = #{rates.inspect}" - assert_not_nil m_usd = ::Currency.Money('1234.56', :USD, :now) + m_usd = ::Currency.Money('1234.56', :USD, :now).should.not == nil # $stderr.puts "m_usd = #{m_usd.to_s(:code => true)}" - assert_not_nil m_eur = m_usd.convert(:EUR) + m_eur = m_usd.convert(:EUR).should.not == nil # $stderr.puts "m_eur = #{m_eur.to_s(:code => true)}" end def assert_h_rates(rates, writer = nil) - assert_not_nil hr0 = rates[0] + hr0 = rates[0].should.not == nil rates.each do | hr | found_hr = nil begin - assert_not_nil found_hr = hr.find_matching_this(:first) + found_hr = hr.find_matching_this(:first).should.not == nil rescue Object => err raise "#{hr.inspect}: #{err}:\n#{err.backtrace.inspect}" end - assert_not_nil hr0 + hr0.should.not == nil - assert_equal hr0.date, hr.date - assert_equal hr0.date_0, hr.date_0 - assert_equal hr0.date_1, hr.date_1 - assert_equal hr0.source, hr.source + hr.date.should == hr0.date + hr.date_0.should == hr0.date_0 + hr.date_1.should == hr0.date_1 + hr.source.should == hr0.source assert_equal_rate(hr, found_hr) assert_rate_defaults(hr, writer) end end def assert_equal_rate(hr0, hr) - assert_equal hr0.c1.to_s, hr.c1.to_s - assert_equal hr0.c2.to_s, hr.c2.to_s - assert_equal hr0.source, hr.source + hr.c1.to_s.should == hr0.c1.to_s + hr.c2.to_s.should == hr0.c2.to_s + hr.source.should == hr0.source assert_equal_float hr0.rate, hr.rate assert_equal_float hr0.rate_avg, hr.rate_avg - assert_equal hr0.rate_samples, hr.rate_samples + hr.rate_samples.should == hr0.rate_samples assert_equal_float hr0.rate_lo, hr.rate_lo assert_equal_float hr0.rate_hi, hr.rate_hi assert_equal_float hr0.rate_date_0, hr.rate_date_0 assert_equal_float hr0.rate_date_1, hr.rate_date_1 - assert_equal hr0.date, hr.date - assert_equal hr0.date_0, hr.date_0 - assert_equal hr0.date_1, hr.date_1 - assert_equal hr0.derived, hr.derived + hr.date.should == hr0.date + hr.date_0.should == hr0.date_0 + hr.date_1.should == hr0.date_1 + hr.derived.should == hr0.derived end def assert_rate_defaults(hr, writer) - assert_equal writer.source.name, hr.source if writer - assert_equal hr.rate, hr.rate_avg - assert_equal hr.rate_samples, 1 - assert_equal hr.rate, hr.rate_lo - assert_equal hr.rate, hr.rate_hi - assert_equal hr.rate, hr.rate_date_0 - assert_equal hr.rate, hr.rate_date_1 + hr.source if writer.should == writer.source.name + hr.rate_avg.should == hr.rate + 1.should == hr.rate_samples + hr.rate_lo.should == hr.rate + hr.rate_hi.should == hr.rate + hr.rate_date_0.should == hr.rate + hr.rate_date_1.should == hr.rate end def assert_equal_float(x1, x2, eps = 0.00001) eps = (x1 * eps).abs assert((x1 - eps) <= x2) assert((x1 + eps) >= x2) end end end # module diff --git a/spec/macro_spec.rb b/spec/macro_spec.rb index d23076d..029f92d 100644 --- a/spec/macro_spec.rb +++ b/spec/macro_spec.rb @@ -1,109 +1,109 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' require 'currency/macro' module Currency class MacroTest < TestBase class Record include ::Currency::Macro attr_accessor :date attr_accessor :gross attr_accessor :tax attr_accessor :net attr_accessor :currency attr_money :gross_money, :value => :gross, :time => :date, :currency => :currency attr_money :tax_money, :value => :tax, :time => :date, :currency => :currency attr_money :net_money, :value => :net, :time => :date, :currency => :currency def initialize self.date = Time.now self.currency = :USD end def compute_net self.net = self.gross - self.tax end def compute_net_money self.net_money = self.gross_money - self.tax_money end end - def setup + before do super end ############################################ # Tests # - def test_read_money + it "read money" do assert_kind_of Record, r = Record.new - assert_not_nil r.gross = 10.00 - assert_equal r.gross_money.to_f, r.gross - assert_equal r.gross_money.currency.code, r.currency - assert_equal r.gross_money.time, r.date + r.gross = 10.00.should.not == nil + r.gross.should == r.gross_money.to_f + r.currency.should == r.gross_money.currency.code + r.date.should == r.gross_money.time r end - def test_write_money_rep + it "write money rep" do assert_kind_of Record, r = Record.new - assert_not_nil r.gross_money = 10.00 - assert_equal r.gross_money.to_f, r.gross - assert_equal r.gross_money.currency.code, r.currency - assert_equal r.gross_money.time, r.date + r.gross_money = 10.00.should.not == nil + r.gross.should == r.gross_money.to_f + r.currency.should == r.gross_money.currency.code + r.date.should == r.gross_money.time r end - def test_money_cache + it "money cache" do r = test_read_money - assert_not_nil r_gross = r.gross - assert r_gross.object_id == r.gross.object_id + r_gross = r.gross.should.not == nil + r_gross.object_id.should == r.gross.object_id # Cache flush - assert_not_nil r.gross = 12.00 - assert_equal r.gross_money.to_f, r.gross - assert r_gross.object_id != r.gross.object_id + r.gross = 12.00.should.not == nil + r.gross.should == r.gross_money.to_f + r_gross.object_id != r.gross.object_id.should.not == nil end - def test_currency + it "currency" do r = test_read_money - assert_not_nil r.gross_money.currency - assert_equal r.gross_money.currency.code, r.currency + r.gross_money.currency.should.not == nil + r.currency.should == r.gross_money.currency.code end - def test_compute + it "compute" do assert_kind_of Record, r = Record.new - assert_not_nil r.gross = 10.00 - assert_not_nil r.tax = 1.50 + r.gross = 10.00.should.not == nil + r.tax = 1.50.should.not == nil r.compute_net - assert_equal 8.50, r.net - assert_equal r.net, r.net_money.to_f + r.net.should == 8.50 + r.net_money.to_f.should == r.net r.compute_net_money - assert_equal 8.50, r.net - assert_equal r.net, r.net_money.to_f + r.net.should == 8.50 + r.net_money.to_f.should == r.net end end # class end # module diff --git a/spec/money_spec.rb b/spec/money_spec.rb index 050ef3f..fda1f2a 100644 --- a/spec/money_spec.rb +++ b/spec/money_spec.rb @@ -1,301 +1,347 @@ -# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> -# See LICENSE.txt for details. +require File.dirname(__FILE__) + '/spec_helper' -require 'test/test_base' -require 'currency' +describe Currency::Money do -module Currency - -class MoneyTest < TestBase - def setup - super - end - - ############################################ - # Simple stuff. - # - - def test_create - assert_kind_of Money, m = Money.new(1.99) - assert_equal m.currency, Currency.default - assert_equal m.currency.code, :USD - - m + it "create" do + m = Currency::Money.new(1.99) + m.should be_kind_of(Currency::Money) + Currency::Currency.default.should == m.currency + :USD.should == m.currency.code end - def test_object_money_method - assert_kind_of Money, m = 1.99.money(:USD) - assert_equal m.currency.code, :USD - assert_equal m.rep, 199 + describe "object money method" do + it "works with a float" do + m = 1.99.money(:USD) + m.should be_kind_of(Currency::Money) + :USD.should == m.currency.code + 19900.should == m.rep + end - assert_kind_of Money, m = 199.money(:CAD) - assert_equal m.currency.code, :CAD - assert_equal m.rep, 19900 + it "works with a FixNum" do + m = 199.money(:CAD) + m.should be_kind_of(Currency::Money) + :CAD.should == m.currency.code + 1990000.should == m.rep + end - assert_kind_of Money, m = "13.98".money(:CAD) - assert_equal m.currency.code, :CAD - assert_equal m.rep, 1398 + it "works with a string" do + m = "13.98".money(:CAD) + m.should be_kind_of(Currency::Money) + :CAD.should == m.currency.code + 139800.should == m.rep + end - assert_kind_of Money, m = "45.99".money(:EUR) - assert_equal m.currency.code, :EUR - assert_equal m.rep, 4599 + it "works with a string again" do + m = "45.99".money(:EUR) + m.should be_kind_of(Currency::Money) + :EUR.should == m.currency.code + 459900.should == m.rep + end end - def test_zero - m = Money.new(0) - assert ! m.negative? - assert m.zero? - assert ! m.positive? - m + def zero_money + @zero_money ||= Currency::Money.new(0) end - - def test_negative - m = Money.new(-1.00, :USD) - assert m.negative? - assert ! m.zero? - assert ! m.positive? - m + + it "zero" do + zero_money.negative?.should_not == true + zero_money.zero?.should_not == nil + zero_money.positive?.should_not == true + end + + def negative_money + @negative_money ||= Currency::Money.new(-1.00, :USD) + end + + it "negative" do + negative_money.negative?.should_not == nil + negative_money.zero?.should_not == true + negative_money.positive?.should_not == true end - def test_positive - m = Money.new(2.99, :USD) - assert ! m.negative? - assert ! m.zero? - assert m.positive? - m + def positive_money + @positive_money ||= Currency::Money.new(2.99, :USD) + end + it "positive" do + positive_money.negative?.should_not == true + positive_money.zero?.should_not == true + positive_money.positive?.should_not == nil end - def test_relational - n = test_negative - z = test_zero - p = test_positive + it "relational" do + n = negative_money + z = zero_money + p = positive_money - assert (n < p) - assert ! (n > p) - assert ! (p < n) - assert (p > n) - assert (p != n) + (n.should < p) + (n > p).should_not == true + (p < n).should_not == true + (p.should > n) + (p != n).should_not == nil - assert (z <= z) - assert (z >= z) + (z.should <= z) + (z.should >= z) - assert (z <= p) - assert (n <= z) - assert (z >= n) + (z.should <= p) + (n.should <= z) + (z.should >= n) - assert n == n - assert p == p + n.should == n + p.should == p - assert z == test_zero + z.should == zero_money end - def test_compare - n = test_negative - z = test_zero - p = test_positive + it "compare" do + n = negative_money + z = zero_money + p = positive_money - assert (n <=> p) == -1 - assert (p <=> n) == 1 - assert (p <=> z) == 1 + (n <=> p).should == -1 + (p <=> n).should == 1 + (p <=> z).should == 1 - assert (n <=> n) == 0 - assert (z <=> z) == 0 - assert (p <=> p) == 0 + (n <=> n).should == 0 + (z <=> z).should == 0 + (p <=> p).should == 0 end - def test_rep - assert_not_nil m = Money.new(123, :USD) - assert m.rep == 12300 + it "rep" do + m = Currency::Money.new(123, :USD) + m.should_not == nil + m.rep.should == 1230000 - assert_not_nil m = Money.new(123.45, :USD) - assert m.rep == 12345 + m = Currency::Money.new(123.45, :USD) + m.should_not == nil + m.rep.should == 1234500 - assert_not_nil m = Money.new("123.456", :USD) - assert m.rep == 12345 + m = Currency::Money.new("123.456", :USD) + m.should_not == nil + m.rep.should == 1234560 end - def test_convert - assert_not_nil m = Money.new("123.456", :USD) - assert m.rep == 12345 + it "convert" do + m = Currency::Money.new("123.456", :USD) + m.should_not == nil + m.rep.should == 1234560 - assert_equal 123, m.to_i - assert_equal 123.45, m.to_f - assert_equal "$123.45", m.to_s + m.to_i.should == 123 + m.to_f.should == 123.456 + m.to_s.should == "$123.4560" end - def test_eql - assert_not_nil usd1 = Money.new(123, :USD) - assert_not_nil usd2 = Money.new("123", :USD) + it "eql" do + usd1 = Currency::Money.new(123, :USD) + usd1.should_not == nil + usd2 = Currency::Money.new("123", :USD) + usd2.should_not == nil - assert_equal :USD, usd1.currency.code - assert_equal :USD, usd2.currency.code + usd1.currency.code.should == :USD + usd2.currency.code.should == :USD - assert_equal usd1.rep, usd2.rep + usd2.rep.should == usd1.rep - assert usd1 == usd2 + usd1.should == usd2 end - def test_not_eql + it "not eql" do - assert_not_nil usd1 = Money.new(123, :USD) - assert_not_nil usd2 = Money.new("123.01", :USD) + usd1 = Currency::Money.new(123, :USD) + usd1.should_not == nil + usd2 = Currency::Money.new("123.01", :USD) + usd2.should_not == nil - assert_equal :USD, usd1.currency.code - assert_equal :USD, usd2.currency.code + usd1.currency.code.should == :USD + usd2.currency.code.should == :USD - assert_not_equal usd1.rep, usd2.rep + usd2.rep.should_not == usd1.rep - assert usd1 != usd2 + (usd1 != usd2).should_not == nil ################ # currency != # rep == - assert_not_nil usd = Money.new(123, :USD) - assert_not_nil cad = Money.new(123, :CAD) + usd = Currency::Money.new(123, :USD) + usd.should_not == nil + cad = Currency::Money.new(123, :CAD) + cad.should_not == nil - assert_equal :USD, usd.currency.code - assert_equal :CAD, cad.currency.code + usd.currency.code.should == :USD + cad.currency.code.should == :CAD - assert_equal usd.rep, cad.rep - assert usd.currency != cad.currency + cad.rep.should == usd.rep + (usd.currency != cad.currency).should_not == nil - assert usd != cad + (usd != cad).should_not == nil end + + describe "operations" do + before(:each) do + @usd = Currency::Money.new(123.45, :USD) + @cad = Currency::Money.new(123.45, :CAD) + end + + it "should work" do + @usd.should_not == nil + @cad.should_not == nil + end + + it "handle negative money" do + # - Currency::Money => Currency::Money + (- @usd).rep.should == -1234500 + (- @usd).currency.code.should == :USD - def test_op - # Using default get_rate - assert_not_nil usd = Money.new(123.45, :USD) - assert_not_nil cad = Money.new(123.45, :CAD) - - # - Money => Money - assert_equal(-12345, (- usd).rep) - assert_equal :USD, (- usd).currency.code - - assert_equal(-12345, (- cad).rep) - assert_equal :CAD, (- cad).currency.code - - # Money + Money => Money - assert_kind_of Money, m = (usd + usd) - assert_equal 24690, m.rep - assert_equal :USD, m.currency.code - - assert_kind_of Money, m = (usd + cad) - assert_equal 22889, m.rep - assert_equal :USD, m.currency.code - - assert_kind_of Money, m = (cad + usd) - assert_equal 26798, m.rep - assert_equal :CAD, m.currency.code - - # Money - Money => Money - assert_kind_of Money, m = (usd - usd) - assert_equal 0, m.rep - assert_equal :USD, m.currency.code - - assert_kind_of Money, m = (usd - cad) - assert_equal 1801, m.rep - assert_equal :USD, m.currency.code - - assert_kind_of Money, m = (cad - usd) - assert_equal -2108, m.rep - assert_equal :CAD, m.currency.code - - # Money * Numeric => Money - assert_kind_of Money, m = (usd * 0.5) - assert_equal 6172, m.rep - assert_equal :USD, m.currency.code - - # Money / Numeric => Money - assert_kind_of Money, m = usd / 3 - assert_equal 4115, m.rep - assert_equal :USD, m.currency.code - - # Money / Money => Numeric - assert_kind_of Numeric, m = usd / Money.new("41.15", :USD) - assert_equal_float 3.0, m + (- @cad).rep.should == -1234500 + (- @cad).currency.code.should == :CAD + end - assert_kind_of Numeric, m = (usd / cad) - assert_equal_float Exchange::Rate::Source::Test.USD_CAD, m, 0.0001 + it "should add monies of the same currency" do + m = (@usd + @usd) + m.should be_kind_of(Currency::Money) + m.rep.should == 2469000 + m.currency.code.should == :USD + end + + it "should add monies of different currencies and return USD" do + m = (@usd + @cad) + m.should be_kind_of(Currency::Money) + m.rep.should == 2288907 + m.currency.code.should == :USD + end + + it "should add monies of different currencies and return CAD" do + m = (@cad + @usd) + m.should be_kind_of(Currency::Money) + m.rep.should == 2679852 + m.currency.code.should == :CAD + end + + it "should subtract monies of the same currency" do + m = (@usd - @usd) + m.should be_kind_of(Currency::Money) + m.rep.should == 0 + m.currency.code.should == :USD + end + + it "should subtract monies of different currencies and return USD" do + m = (@usd - @cad) + m.should be_kind_of(Currency::Money) + m.rep.should == 180093 + m.currency.code.should == :USD + end + + it "should subtract monies of different currencies and return CAD" do + m = (@cad - @usd) + m.should be_kind_of(Currency::Money) + m.rep.should == -210852 + m.currency.code.should == :CAD + end + + it "should multiply by numerics and return money" do + m = (@usd * 0.5) + m.should be_kind_of(Currency::Money) + m.rep.should == 617250 + m.currency.code.should == :USD + end + + it "should divide by numerics and return money" do + m = @usd / 3 + m.should be_kind_of(Currency::Money) + m.rep.should == 411500 + m.currency.code.should == :USD + end + + it "should divide by monies of the same currency and return numeric" do + m = @usd / Currency::Money.new("41.15", :USD) + m.should be_kind_of(Numeric) + m.should be_close(3.0, 1.0e-8) + end + + it "should divide by monies of different currencies and return numeric" do + m = (@usd / @cad) + m.should be_kind_of(Numeric) + m.should be_close(Currency::Exchange::Rate::Source::Test.USD_CAD, 0.0001) + end end - - def test_pivot_conversions + it "pivot conversions" do # Using default get_rate - assert_not_nil cad = Money.new(123.45, :CAD) - assert_not_nil eur = cad.convert(:EUR) - assert_kind_of Numeric, m = (eur.to_f / cad.to_f) - m_expected = (1.0 / Exchange::Rate::Source::Test.USD_CAD) * Exchange::Rate::Source::Test.USD_EUR - # $stderr.puts "m = #{m}, expected = #{m_expected}" - assert_equal_float m_expected, m, 0.001 - - - assert_not_nil gbp = Money.new(123.45, :GBP) - assert_not_nil eur = gbp.convert(:EUR) - assert_kind_of Numeric, m = (eur.to_f / gbp.to_f) - m_expected = (1.0 / Exchange::Rate::Source::Test.USD_GBP) * Exchange::Rate::Source::Test.USD_EUR - # $stderr.puts "m = #{m}, expected = #{m_expected}" - assert_equal_float m_expected, m, 0.001 + cad = Currency::Money.new(123.45, :CAD) + cad.should_not == nil + eur = cad.convert(:EUR) + eur.should_not == nil + m = (eur.to_f / cad.to_f) + m.should be_kind_of(Numeric) + m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_CAD) * Currency::Exchange::Rate::Source::Test.USD_EUR + m.should be_close(m_expected, 0.001) + + + gbp = Currency::Money.new(123.45, :GBP) + gbp.should_not == nil + eur = gbp.convert(:EUR) + eur.should_not == nil + m = (eur.to_f / gbp.to_f) + m.should be_kind_of(Numeric) + m_expected = (1.0 / Currency::Exchange::Rate::Source::Test.USD_GBP) * Currency::Exchange::Rate::Source::Test.USD_EUR + m.should be_close(m_expected, 0.001) end - def test_invalid_currency_code - assert_raise Exception::InvalidCurrencyCode do - Money.new(123, :asdf) - end - assert_raise Exception::InvalidCurrencyCode do - Money.new(123, 5) - end + it "invalid currency code" do + lambda {Currency::Money.new(123, :asdf)}.should raise_error(Currency::Exception::InvalidCurrencyCode) + lambda {Currency::Money.new(123, 5)}.should raise_error(Currency::Exception::InvalidCurrencyCode) end - def test_time_default - Money.default_time = nil + it "time default" do + Currency::Money.default_time = nil - assert_not_nil usd = Money.new(123.45, :USD) - assert_nil usd.time + usd = Currency::Money.new(123.45, :USD) + usd.should_not == nil + usd.time.should == nil - Money.default_time = Time.now - assert_not_nil usd = Money.new(123.45, :USD) - assert_equal usd.time, Money.default_time + Currency::Money.default_time = Time.now + usd = Currency::Money.new(123.45, :USD) + usd.should_not == nil + Currency::Money.default_time.should == usd.time end - def test_time_now - # Test - Money.default_time = :now + it "time now" do + Currency::Money.default_time = :now - assert_not_nil usd = Money.new(123.45, :USD) - assert_not_nil usd.time + usd = Currency::Money.new(123.45, :USD) + usd.should_not == nil + usd.time.should_not == nil sleep 1 - assert_not_nil usd2 = Money.new(123.45, :USD) - assert_not_nil usd2.time - assert usd.time != usd2.time + usd2 = Currency::Money.new(123.45, :USD) + usd2.should_not == nil + usd2.time.should_not == nil + (usd.time != usd2.time).should_not == nil - Money.default_time = nil + Currency::Money.default_time = nil end - def test_time_fixed - # Test for fixed time. - Money.default_time = Time.new + it "time fixed" do + Currency::Money.default_time = Time.new - assert_not_nil usd = Money.new(123.45, :USD) - assert_not_nil usd.time + usd = Currency::Money.new(123.45, :USD) + usd.should_not == nil + usd.time.should_not == nil sleep 1 - assert_not_nil usd2 = Money.new(123.45, :USD) - assert_not_nil usd2.time - assert usd.time == usd2.time + usd2 = Currency::Money.new(123.45, :USD) + usd2.should_not == nil + usd2.time.should_not == nil + usd.time.should == usd2.time end - -end # class - -end # module +end diff --git a/spec/new_york_fed_spec.rb b/spec/new_york_fed_spec.rb index 569606f..7153167 100644 --- a/spec/new_york_fed_spec.rb +++ b/spec/new_york_fed_spec.rb @@ -1,73 +1,73 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' # For :type => :money require 'currency/exchange/rate/source/new_york_fed' module Currency class NewYorkFedTest < TestBase - def setup + before do super end @@available = nil # New York Fed rates are not available on Saturday and Sunday. def available? if @@available == nil @@available = @source.available? STDERR.puts "Warning: NewYorkFed unavailable on Saturday and Sunday, skipping tests." end @@available end def get_rate_source # Force NewYorkFed Exchange. verbose = false source = @source = Exchange::Rate::Source::NewYorkFed.new(:verbose => verbose) deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) end - def test_usd_cad + it "usd cad" do return unless available? - assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates - assert_not_nil rates[:USD] - assert_not_nil usd_cad = rates[:USD][:CAD] + rates = Exchange::Rate::Source.default.source.raw_rates.should.not == nil + rates[:USD].should.not == nil + usd_cad = rates[:USD][:CAD].should.not == nil - assert_not_nil usd = Money.new(123.45, :USD) - assert_not_nil cad = usd.convert(:CAD) + usd = Money.new(123.45, :USD).should.not == nil + cad = usd.convert(:CAD).should.not == nil assert_kind_of Numeric, m = (cad.to_f / usd.to_f) # $stderr.puts "m = #{m}" assert_equal_float usd_cad, m, 0.001 end - def test_cad_eur + it "cad eur" do return unless available? - assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates - assert_not_nil rates[:USD] - assert_not_nil usd_cad = rates[:USD][:CAD] - assert_not_nil usd_eur = rates[:USD][:EUR] + rates = Exchange::Rate::Source.default.source.raw_rates.should.not == nil + rates[:USD].should.not == nil + usd_cad = rates[:USD][:CAD].should.not == nil + usd_eur = rates[:USD][:EUR].should.not == nil - assert_not_nil cad = Money.new(123.45, :CAD) - assert_not_nil eur = cad.convert(:EUR) + cad = Money.new(123.45, :CAD).should.not == nil + eur = cad.convert(:EUR).should.not == nil assert_kind_of Numeric, m = (eur.to_f / cad.to_f) # $stderr.puts "m = #{m}" assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 end end end # module diff --git a/spec/parser_spec.rb b/spec/parser_spec.rb index 7def4bc..f124def 100644 --- a/spec/parser_spec.rb +++ b/spec/parser_spec.rb @@ -1,105 +1,105 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' module Currency class ParserTest < TestBase - def setup + before do super @parser = ::Currency::Currency.USD.parser_or_default end ############################################ # Simple stuff. # - def test_default + it "default" do end - def test_thousands - assert_equal 123456789, @parser.parse("1234567.89").rep + it "thousands" do + @parser.parse("1234567.89").rep.should == 123456789 assert_equal 123456789, @parser.parse("1,234,567.89").rep end - def test_cents - assert_equal 123456789, @parser.parse("1234567.89").rep - assert_equal 123456700, @parser.parse("1234567").rep - assert_equal 123456700, @parser.parse("1234567.").rep - assert_equal 123456780, @parser.parse("1234567.8").rep - assert_equal 123456789, @parser.parse("1234567.891").rep - assert_equal -123456700, @parser.parse("-1234567").rep - assert_equal 123456700, @parser.parse("+1234567").rep + it "cents" do + @parser.parse("1234567.89").rep.should == 123456789 + @parser.parse("1234567").rep.should == 123456700 + @parser.parse("1234567.").rep.should == 123456700 + @parser.parse("1234567.8").rep.should == 123456780 + @parser.parse("1234567.891").rep.should == 123456789 + @parser.parse("-1234567").rep.should == -123456700 + @parser.parse("+1234567").rep.should == 123456700 end - def test_misc - assert_not_nil m = "123.45 USD".money + "100 CAD" - assert ! (m.rep == 200.45) + it "misc" do + m = "123.45 USD".money + "100 CAD".should.not == nil + (m.rep == 200.45).should.not == true end - def test_round_trip + it "round trip" do ::Currency::Currency.default = :USD - assert_not_nil m = ::Currency::Money("1234567.89", :CAD) - assert_not_nil m2 = ::Currency::Money(m.inspect) - assert_equal m.rep, m2.rep - assert_equal m.currency, m2.currency - assert_nil m2.time - assert_equal m.inspect, m2.inspect + m = ::Currency::Money("1234567.89", :CAD).should.not == nil + m2 = ::Currency::Money(m.inspect).should.not == nil + m2.rep.should == m.rep + m2.currency.should == m.currency + m2.time.should == nil + m2.inspect.should == m.inspect end - def test_round_trip_time + it "round trip time" do ::Currency::Currency.default = :USD time = Time.now.getutc - assert_not_nil m = ::Currency::Money("1234567.89", :CAD, time) - assert_not_nil m.time - assert_not_nil m2 = ::Currency::Money(m.inspect) - assert_not_nil m2.time - assert_equal m.rep, m2.rep - assert_equal m.currency, m2.currency - assert_equal m.time.to_i, m2.time.to_i - assert_equal m.inspect, m2.inspect + m = ::Currency::Money("1234567.89", :CAD, time).should.not == nil + m.time.should.not == nil + m2 = ::Currency::Money(m.inspect).should.not == nil + m2.time.should.not == nil + m2.rep.should == m.rep + m2.currency.should == m.currency + m2.time.to_i.should == m.time.to_i + m2.inspect.should == m.inspect end - def test_time_nil + it "time nil" do parser = ::Currency::Parser.new parser.time = nil - assert_not_nil m = parser.parse("$1234.55") - assert_equal nil, m.time + m = parser.parse("$1234.55").should.not == nil + m.time.should == nil end - def test_time + it "time" do parser = ::Currency::Parser.new parser.time = Time.new - assert_not_nil m = parser.parse("$1234.55") - assert_equal parser.time, m.time + m = parser.parse("$1234.55").should.not == nil + m.time.should == parser.time end - def test_time_now + it "time now" do parser = ::Currency::Parser.new parser.time = :now - assert_not_nil m = parser.parse("$1234.55") - assert_not_nil m1_time = m.time + m = parser.parse("$1234.55").should.not == nil + m1_time = m.time.should.not == nil - assert_not_nil m = parser.parse("$1234.55") - assert_not_nil m2_time = m.time + m = parser.parse("$1234.55").should.not == nil + m2_time = m.time.should.not == nil assert_not_equal m1_time, m2_time end end end # module diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 3a5b820..f863a69 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,44 +1,25 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. -# Base Test class - -require 'test/unit' +require 'spec' require 'currency' require 'currency/exchange/rate/source/test' -module Currency - -class TestBase < Test::Unit::TestCase - def setup - super - @rate_source ||= get_rate_source - Exchange::Rate::Source.default = @rate_source - - # Force non-historical money values. - Money.default_time = nil - end - - - def get_rate_source - source = Exchange::Rate::Source::Test.instance - deriver = Exchange::Rate::Deriver.new(:source => source) - end - - # Avoid "No test were specified" error. - def test_foo - assert true - end +def setup + rate_source ||= get_rate_source + Currency::Exchange::Rate::Source.default = rate_source + # Force non-historical money values. + Currency::Money.default_time = nil +end - # Helpers. - def assert_equal_float(x, y, eps = 1.0e-8) - d = (x * eps).abs - assert((x - d) <= y) - assert(y <= (x + d)) - end +def get_rate_source + source = Currency::Exchange::Rate::Source::Test.instance + Currency::Exchange::Rate::Deriver.new(:source => source) +end -end # class +Spec::Runner.configure do |config| + config.before(:all) {setup} +end -end # module diff --git a/spec/time_quantitizer_spec.rb b/spec/time_quantitizer_spec.rb index 10cc5a5..6fc70fc 100644 --- a/spec/time_quantitizer_spec.rb +++ b/spec/time_quantitizer_spec.rb @@ -1,136 +1,136 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. #require File.dirname(__FILE__) + '/../test_helper' require 'test/test_base' require 'currency/exchange/time_quantitizer' module Currency module Exchange class TimeQuantitizerTest < TestBase - def setup + before do super end ############################################ # # - def test_create + it "create" do assert_kind_of TimeQuantitizer, tq = TimeQuantitizer.new() - assert_equal 60 * 60 * 24, tq.time_quant_size - assert_nil tq.quantitize_time(nil) + tq.time_quant_size.should == 60 * 60 * 24 + tq.quantitize_time(nil).should == nil tq end - def test_localtime + it "localtime" do t1 = assert_test_day(t0 = Time.new) - assert_equal t0.utc_offset, t1.utc_offset - assert_equal Time.now.utc_offset, t1.utc_offset + t1.utc_offset.should == t0.utc_offset + t1.utc_offset.should == Time.now.utc_offset end - def test_utc + it "utc" do t1 = assert_test_day(t0 = Time.new.utc) - assert_equal t0.utc_offset, t1.utc_offset + t1.utc_offset.should == t0.utc_offset end - def test_random + it "random" do (1 .. 1000).each do t0 = Time.at(rand(1234567901).to_i) assert_test_day(t0) assert_test_hour(t0) # Problem year? t0 = Time.parse('1977/01/01') + rand(60 * 60 * 24 * 7 * 52).to_i assert_test_day(t0) assert_test_hour(t0) # Problem year? t0 = Time.parse('1995/01/01') + rand(60 * 60 * 24 * 7 * 52).to_i assert_test_day(t0) assert_test_hour(t0) end end def assert_test_day(t0) tq = test_create begin - assert_not_nil t1 = tq.quantitize_time(t0) + t1 = tq.quantitize_time(t0).should.not == nil #$stderr.puts "t0 = #{t0}" #$stderr.puts "t1 = #{t1}" - assert_equal t0.year, t1.year - assert_equal t0.month, t1.month - assert_equal t0.day, t1.day + t1.year.should == t0.year + t1.month.should == t0.month + t1.day.should == t0.day assert_time_beginning_of_day(t1) rescue Object => err raise("#{err}\nDuring quantitize_time(#{t0} (#{t0.to_i}))") end t1 end def assert_test_hour(t0) tq = TimeQuantitizer.new(:time_quant_size => 60 * 60) # 1 hour - assert_not_nil t1 = tq.quantitize_time(t0) + t1 = tq.quantitize_time(t0).should.not == nil #$stderr.puts "t0 = #{t0}" #$stderr.puts "t1 = #{t1}" - assert_equal t0.year, t1.year - assert_equal t0.month, t1.month - assert_equal t0.day, t1.day + t1.year.should == t0.year + t1.month.should == t0.month + t1.day.should == t0.day assert_time_beginning_of_hour(t1) t1 end def assert_test_minute(t0) tq = TimeQuantitizer.new(:time_quant_size => 60) # 1 minute tq.local_timezone_offset - assert_not_nil t1 = tq.quantitize_time(t0) + t1 = tq.quantitize_time(t0).should.not == nil $stderr.puts "t0 = #{t0}" $stderr.puts "t1 = #{t1}" - assert_equal t0.year, t1.year - assert_equal t0.month, t1.month - assert_equal t0.day, t1.day + t1.year.should == t0.year + t1.month.should == t0.month + t1.day.should == t0.day assert_time_beginning_of_day(t1) t1 end def assert_time_beginning_of_day(t1) - assert_equal 0, t1.hour + t1.hour.should == 0 assert_time_beginning_of_hour(t1) end def assert_time_beginning_of_hour(t1) - assert_equal 0, t1.min + t1.min.should == 0 assert_time_beginning_of_min(t1) end def assert_time_beginning_of_min(t1) - assert_equal 0, t1.sec + t1.sec.should == 0 end end # class end # module end # module diff --git a/spec/timed_cache_spec.rb b/spec/timed_cache_spec.rb index 98e3b4c..93e98e9 100644 --- a/spec/timed_cache_spec.rb +++ b/spec/timed_cache_spec.rb @@ -1,95 +1,95 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. require 'test/test_base' require 'currency' require 'currency/exchange/rate/source/xe' require 'currency/exchange/rate/source/timed_cache' module Currency class TimedCacheTest < TestBase - def setup + before do super end def get_rate_source @source = source = Exchange::Rate::Source::Xe.new # source.verbose = true deriver = Exchange::Rate::Deriver.new(:source => source) @cache = cache = Exchange::Rate::Source::TimedCache.new(:source => deriver) cache end - def test_timed_cache_usd_cad - assert_not_nil rates = @source.raw_rates - assert_not_nil rates[:USD] - assert_not_nil usd_cad = rates[:USD][:CAD] + it "timed cache usd cad" do + rates = @source.raw_rates.should.not == nil + rates[:USD].should.not == nil + usd_cad = rates[:USD][:CAD].should.not == nil - assert_not_nil usd = Money.new(123.45, :USD) - assert_not_nil cad = usd.convert(:CAD) + usd = Money.new(123.45, :USD).should.not == nil + cad = usd.convert(:CAD).should.not == nil assert_kind_of Numeric, m = (cad.to_f / usd.to_f) # $stderr.puts "m = #{m}" assert_equal_float usd_cad, m, 0.001 end - def test_timed_cache_cad_eur - assert_not_nil rates = @source.raw_rates - assert_not_nil rates[:USD] - assert_not_nil usd_cad = rates[:USD][:CAD] - assert_not_nil usd_eur = rates[:USD][:EUR] + it "timed cache cad eur" do + rates = @source.raw_rates.should.not == nil + rates[:USD].should.not == nil + usd_cad = rates[:USD][:CAD].should.not == nil + usd_eur = rates[:USD][:EUR].should.not == nil - assert_not_nil cad = Money.new(123.45, :CAD) - assert_not_nil eur = cad.convert(:EUR) + cad = Money.new(123.45, :CAD).should.not == nil + eur = cad.convert(:EUR).should.not == nil assert_kind_of Numeric, m = (eur.to_f / cad.to_f) # $stderr.puts "m = #{m}" assert_equal_float((1.0 / usd_cad) * usd_eur, m, 0.001) end - def test_reload + it "reload" do # @cache.verbose = 5 test_timed_cache_cad_eur - assert_not_nil rates = @source.raw_rates - assert_not_nil rates[:USD] - assert_not_nil usd_cad_1 = rates[:USD][:CAD] + rates = @source.raw_rates.should.not == nil + rates[:USD].should.not == nil + usd_cad_1 = rates[:USD][:CAD].should.not == nil - assert_not_nil t1 = @cache.rate_load_time - assert_not_nil t1_reload = @cache.rate_reload_time - assert t1_reload.to_i > t1.to_i + t1 = @cache.rate_load_time.should.not == nil + t1_reload = @cache.rate_reload_time.should.not == nil + t1_reload.to_i.should > t1.to_i @cache.time_to_live = 5 @cache.time_to_live_fudge = 0 # puts @cache.rate_reload_time.to_i - @cache.rate_load_time.to_i - assert @cache.rate_reload_time.to_i - @cache.rate_load_time.to_i == @cache.time_to_live + @cache.rate_reload_time.to_i - @cache.rate_load_time.to_i == @cache.time_to_live.should.not == nil sleep 10 test_timed_cache_cad_eur - assert_not_nil t2 = @cache.rate_load_time - assert t1.to_i != t2.to_i + t2 = @cache.rate_load_time.should.not == nil + t1.to_i != t2.to_i.should.not == nil - assert_not_nil rates = @source.raw_rates - assert_not_nil rates[:USD] - assert_not_nil usd_cad_2 = rates[:USD][:CAD] + rates = @source.raw_rates.should.not == nil + rates[:USD].should.not == nil + usd_cad_2 = rates[:USD][:CAD].should.not == nil - assert usd_cad_1.object_id != usd_cad_2.object_id + usd_cad_1.object_id != usd_cad_2.object_id.should.not == nil end end end # module diff --git a/spec/xe_spec.rb b/spec/xe_spec.rb index ace29d8..a3ee900 100644 --- a/spec/xe_spec.rb +++ b/spec/xe_spec.rb @@ -1,56 +1,50 @@ # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> # See LICENSE.txt for details. -require 'test/test_base' - -require 'currency' # For :type => :money require 'currency/exchange/rate/source/xe' -module Currency - -class XeTest < TestBase - def setup - super +describe Currency::Exchange::Rate::Source::XE do + + before(:all) do + get_rate_source end - def get_rate_source - source = Exchange::Rate::Source::Xe.new - # source.verbose = true - deriver = Exchange::Rate::Deriver.new(:source => source) - deriver + source = Currency::Exchange::Rate::Source::XE.new + Currency::Exchange::Rate::Deriver.new(:source => source) end + it "xe usd cad" do + rates = Currency::Exchange::Rate::Source.default.source.raw_rates + rates.should_not == nil + rates[:USD].should_not == nil + usd_cad = rates[:USD][:CAD].should_not == nil - def test_xe_usd_cad - assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates - assert_not_nil rates[:USD] - assert_not_nil usd_cad = rates[:USD][:CAD] + usd = Currency::Money.new(123.45, :USD) + usd.should_not == nil + cad = usd.convert(:CAD).should_not == nil - assert_not_nil usd = Money.new(123.45, :USD) - assert_not_nil cad = usd.convert(:CAD) - - assert_kind_of Numeric, m = (cad.to_f / usd.to_f) - # $stderr.puts "m = #{m}" - assert_equal_float usd_cad, m, 0.001 + m = (cad.to_f / usd.to_f) + m.should be_kind_of(Numeric) + m.should be_close(usd_cad, 0.001) end - def test_xe_cad_eur - assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates - assert_not_nil rates[:USD] - assert_not_nil usd_cad = rates[:USD][:CAD] - assert_not_nil usd_eur = rates[:USD][:EUR] + it "xe cad eur" do + rates = Currency::Exchange::Rate::Source.default.source.raw_rates + rates.should_not == nil + rates[:USD].should_not == nil + usd_cad = rates[:USD][:CAD].should_not == nil + usd_eur = rates[:USD][:EUR].should_not == nil - assert_not_nil cad = Money.new(123.45, :CAD) - assert_not_nil eur = cad.convert(:EUR) + cad = Currency::Money.new(123.45, :CAD) + cad.should_not == nil + eur = cad.convert(:EUR) + eur.should_not == nil - assert_kind_of Numeric, m = (eur.to_f / cad.to_f) - # $stderr.puts "m = #{m}" - assert_equal_float((1.0 / usd_cad) * usd_eur, m, 0.001) + m = (eur.to_f / cad.to_f) + m.should be_kind_of(Numeric) + m.should be_close((1.0 / usd_cad) * usd_eur, 0.001) end end - -end # module -
acvwilson/currency
2ecca686dcfce62ee7d41d85fdca6a1c22f1c8ce
Initial Import of currency gem spörk
diff --git a/COPYING.txt b/COPYING.txt new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/COPYING.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 0000000..49b8b46 --- /dev/null +++ b/ChangeLog @@ -0,0 +1,8 @@ +2006-10-30 Kurt A. Stephens <[email protected]> + + * Fix gem packaging error. + +2006-10-29 Kurt Stephens <[email protected]> + + * Initial release + diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..ca1ac3c --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,65 @@ +This software distribution is Copyright (c) 2006-2007 +by Kurt Stephens <ruby-currency(at)umleta.com>. + +THERE IS ABSOLUTELY NO WARRANTY: SEE COPYING.txt + +================================================================== + +The following is a minor adaptation of the Ruby Language License. +http://www.ruby-lang.org/en/LICENSE.txt + +================================================================== + +You can redistribute it and/or modify it under either the terms of the GPL +(see COPYING.txt file), or the conditions below: + + 1. You may make and give away verbatim copies of the source form of the + software without restriction, provided that you duplicate all of the + original copyright notices and associated disclaimers. + + 2. You may modify your copy of the software in any way, provided that + you do at least ONE of the following: + + a) place your modifications in the Public Domain or otherwise + make them Freely Available, such as by posting said + modifications to Usenet or an equivalent medium, or by allowing + the author to include your modifications in the software. + + b) use the modified software only within your corporation or + organization. + + c) rename any non-standard executables so the names do not conflict + with standard executables, which must also be provided. + + d) make other distribution arrangements with the author. + + 3. You may distribute the software in object code or executable + form, provided that you do at least ONE of the following: + + a) distribute the executables and library files of the software, + together with instructions (in the manual page or equivalent) + on where to get the original distribution. + + b) accompany the distribution with the machine-readable source of + the software. + + c) give non-standard executables non-standard names, with + instructions on where to get the original software distribution. + + d) make other distribution arrangements with the author. + + 4. You may modify and include the part of the software into any other + software (possibly commercial). But some files in the distribution + are not written by the author, so that they are not under this terms. + + 5. The scripts and library files supplied as input to or produced as + output from the software do not automatically fall under the + copyright of the software, but belong to whomever generated them, + and may be sold commercially, and may be aggregated with this + software. + + 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. + diff --git a/Manifest.txt b/Manifest.txt new file mode 100644 index 0000000..f631c9b --- /dev/null +++ b/Manifest.txt @@ -0,0 +1,58 @@ +COPYING.txt +ChangeLog +LICENSE.txt +Manifest.txt +README.txt +Rakefile +Releases.txt +TODO.txt +bin/currency_historical_rate_load +examples/ex1.rb +examples/xe1.rb +lib/currency.rb +lib/currency/active_record.rb +lib/currency/config.rb +lib/currency/core_extensions.rb +lib/currency/currency.rb +lib/currency/currency/factory.rb +lib/currency/currency_version.rb +lib/currency/exception.rb +lib/currency/exchange.rb +lib/currency/exchange/rate.rb +lib/currency/exchange/rate/deriver.rb +lib/currency/exchange/rate/source.rb +lib/currency/exchange/rate/source/base.rb +lib/currency/exchange/rate/source/failover.rb +lib/currency/exchange/rate/source/federal_reserve.rb +lib/currency/exchange/rate/source/historical.rb +lib/currency/exchange/rate/source/historical/rate.rb +lib/currency/exchange/rate/source/historical/rate_loader.rb +lib/currency/exchange/rate/source/historical/writer.rb +lib/currency/exchange/rate/source/new_york_fed.rb +lib/currency/exchange/rate/source/provider.rb +lib/currency/exchange/rate/source/test.rb +lib/currency/exchange/rate/source/the_financials.rb +lib/currency/exchange/rate/source/timed_cache.rb +lib/currency/exchange/rate/source/xe.rb +lib/currency/exchange/time_quantitizer.rb +lib/currency/formatter.rb +lib/currency/macro.rb +lib/currency/money.rb +lib/currency/money_helper.rb +lib/currency/parser.rb +test/ar_column_test.rb +test/ar_simple_test.rb +test/ar_test_base.rb +test/ar_test_core.rb +test/config_test.rb +test/federal_reserve_test.rb +test/formatter_test.rb +test/historical_writer_test.rb +test/macro_test.rb +test/money_test.rb +test/new_york_fed_test.rb +test/parser_test.rb +test/test_base.rb +test/time_quantitizer_test.rb +test/timed_cache_test.rb +test/xe_test.rb diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..bffc4e0 --- /dev/null +++ b/README.txt @@ -0,0 +1,51 @@ += Currency + +This is the rubyforge.com Currency package. + +== Installation + +gem install currency + +== Documentation + +"Project Info":http://rubyforge.org/projects/currency/ + +"API Documentation":http://currency.rubyforge.org/ + +The RubyForge package currency +implements an object-oriented representation of currencies, monetary values, foreign exchanges and rates. + +Currency::Money uses a scaled integer representation of the monetary value and performs accurate conversions from string values. + +See also: http://umleta.com/node/5 + +== Home page + +* {Currency Home}[http://currency.rubyforge.org] + +== Additional directories + +[./lib/...] the Currency library +[./test/...] unit and functional test +[./examples/...] example programs + +== Credits + +Currency was developed by: + +* Kurt Stephens -- ruby-currency(at)umleta.com, sponsored by umleta.com + +== License + +* See LICENSE.txt + +== Copyright + +* Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> + +== Contributors + +* Steffen Rusitschka + + + diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..cee1b87 --- /dev/null +++ b/Rakefile @@ -0,0 +1,167 @@ +# Rakefile for currency -*- ruby -*- +# Adapted from RubyGems/Rakefile + +# For release +" +rake make_manifest +rake update_version +svn status +rake package +rake release VERSION=x.x.x +rake svn_release +rake publish_docs +rake announce +" + +################################################################# + +require 'rubygems' +require 'hoe' + +PKG_Name = 'Currency' +PKG_DESCRIPTION = %{Currency models currencies, monetary values, foreign exchanges rates. +Pulls live and historical rates from http://xe.com/, http://newyorkfed.org/, http://thefinancials.com/. +Can store/retrieve historical rate data from database using ActiveRecord. +Can store/retrieve Money values using ActiveRecord. + +For more details, see: + +http://rubyforge.org/projects/currency/ +http://currency.rubyforge.org/ +http://currency.rubyforge.org/files/README_txt.html + +} + +################################################################# +# Release notes +# + +def get_release_notes(relfile = "Releases.txt") + + release = nil + notes = [ ] + + File.open(relfile) do |f| + while ! f.eof && line = f.readline + if md = /^== Release ([\d\.]+)/i.match(line) + release = md[1] + notes << line + break + end + end + + while ! f.eof && line = f.readline + if md = /^== Release ([\d\.]+)/i.match(line) + break + end + notes << line + end + end + + [ release, notes.join('') ] +end + +################################################################# + +PKG_NAME = PKG_Name.gsub(/[a-z][A-Z]/) {|x| "#{x[0,1]}_#{x[1,1]}"}.downcase + +PKG_SVN_ROOT="svn+ssh://rubyforge.org/var/svn/#{PKG_NAME}/#{PKG_NAME}" + +release, release_notes = get_release_notes + +hoe = Hoe.new(PKG_Name.downcase, release) do |p| + p.author = 'Kurt Stephens' + p.description = PKG_DESCRIPTION + p.email = "ruby-#{PKG_NAME}@umleta.com" + p.summary = p.description + p.changes = release_notes + p.url = "http://rubyforge.org/projects/#{PKG_NAME}" + + p.test_globs = ['test/**/*.rb'] +end + +PKG_VERSION = hoe.version + +################################################################# +# Version file +# + +def announce(msg='') + STDERR.puts msg +end + +version_rb = "lib/#{PKG_NAME}/#{PKG_NAME}_version.rb" + +task :update_version do + announce "Updating #{PKG_Name} version to #{PKG_VERSION}: #{version_rb}" + open(version_rb, "w") do |f| + f.puts "module #{PKG_Name}" + f.puts " #{PKG_Name}Version = '#{PKG_VERSION}'" + f.puts "end" + f.puts "# DO NOT EDIT" + f.puts "# This file is auto-generated by build scripts." + f.puts "# See: rake update_version" + end + if ENV['RELTEST'] + announce "Release Task Testing, skipping commiting of new version" + else + sh %{svn commit -m "Updated to version #{PKG_VERSION}" #{version_rb} Releases.txt ChangeLog Rakefile Manifest.txt} + end +end + +task version_rb => :update_version + +################################################################# +# SVN +# + +task :svn_release do + sh %{svn cp -m 'Release #{PKG_VERSION}' . #{PKG_SVN_ROOT}/release/#{PKG_VERSION}} +end + +# task :test => :update_version + + +# Misc Tasks --------------------------------------------------------- + +def egrep(pattern) + Dir['**/*.rb'].each do |fn| + count = 0 + open(fn) do |f| + while line = f.gets + count += 1 + if line =~ pattern + puts "#{fn}:#{count}:#{line}" + end + end + end + end +end + +desc "Look for TODO and FIXME tags in the code" +task :todo do + egrep /#.*(FIXME|TODO|TBD)/ +end + +desc "Look for Debugging print lines" +task :dbg do + egrep /\bDBG|\bbreakpoint\b/ +end + +desc "List all ruby files" +task :rubyfiles do + puts Dir['**/*.rb'].reject { |fn| fn =~ /^pkg/ } + puts Dir['bin/*'].reject { |fn| fn =~ /CVS|.svn|(~$)|(\.rb$)/ } +end + +task :make_manifest do + open("Manifest.txt", "w") do |f| + f.puts Dir['**/*'].reject { |fn| + fn == 'email.txt' || + ! test(?f, fn) || + fn =~ /CVS|.svn|([#~]$)|(.gem$)|(^pkg\/)|(^doc\/)/ + }.sort.join("\n") + "\n" + end +end + + diff --git a/Releases.txt b/Releases.txt new file mode 100644 index 0000000..db4a040 --- /dev/null +++ b/Releases.txt @@ -0,0 +1,155 @@ += Currency Release History + +== Release 0.4.11: 2007/11/02 + +CRITICAL FIXES + +* parser.rb - uncommitted typos. + +== Release 0.4.10: 2007/11/01 + +CRITICAL FIXES + +* xe.rb - http://xe.com format change: Handle inline div in rates table. +* bin/currency_historical_rate_load - script for pulling rates from sources into historical rate table. +* exception.rb - Currency::Exception::Base can take Array with optional key/values. +* exception.rb - Additional exception classes. +* ALL - use raise instead of throw throughout. + + +== Release 0.4.9: 2007/11/01 + +** IGNORE THIS RELEASE** + +* Broken rubyforge config. + +== Release 0.4.7: 2007/06/25 + +CRITICAL FIXES + +* NewYorkFed: CRITICAL FIX: + + Rates for USDAUD, USDEUR, USDNZD and USDGBP were reciprocals. + See http://www.newyorkfed.org/markets/fxrates/noon.cfm + +* FederalReserve: Added support for historical rates from http://www.federalreserve.gov/releases/H10/hist +* Provider#get_rate(): Return first rate immediately. +* Rate::Writable for rate summary computation support. +* Rate: collect_rate(): fixed rate_date_1. +* Historical::Rate: to_rate(): takes optional class. +* Historical::Rate: from_rate(): fixed rate_samples. + +== Release 0.4.6: 2007/05/29 + +* NewYorkFed: changed FEXtime to FEXTIME. +* Fixed Rate#collect_rates, source, rate_date_0, rate_date_1. + +== Release 0.4.5: 2007/05/29 + +* Historical::Rate table name can be configured in Currency::Config.current.historical_table_name +* Fixed Rate::Source::TheFinancials. +* Examples: use Currency.Money(), not Currency::Money.new(). + +== Release 0.4.4: 2007/04/01 + +MAY NOT BE BACKWARDS-COMPATIBLE + +* Fixed TimedCache. +* Updated documentation. +* Added support for Parser#time = :now. +* Added support for Time in Formatter and Parser using Time#xmlschema. +* Money#inspect now appends Money#time, if set. + +== Release 0.4.3: 2007/04/01 + +* Added available? checks for NewYorkFed. +* Created new UnavailableRates exception for rate providers that return no rates (New York Fed on weekends). +* Fixed xe.com rate dates. +* Refactored exceptions. +* Fixed comments. + +== Release 0.4.2: 2007/03/11 + +* Missing Manifest changes +* Missing Contributors + +== Release 0.4.1: 2007/03/10 + +Some changes are not backwards-compatible + +* Fixed Rate::Source::Xe; site format changed, more robust parser. +* Added Currency::Config. +* Support for filtering Float values before casting to Money, based on suggestions for rounding by Steffen Rusitschka. +* Fixed :allow_nil in ActiveRecord money macro based on fix by Steffen Rusitschka. +* Fixed package scoping issue in Money. +* Added support for Formatter#template string +* Money format template default changed to '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}'. THIS MAY BREAK EXISTING CLIENTS. See http://www.jhall.demon.co.uk/currency/ for rationale. + +== Release 0.4.0: 2007/02/21 + +=== MAJOR CHANGES IN THIS RELEASE FOR HISTORICAL RATE DATA + +Some changes are not backwards-compatible + +* ActiveRecord::Base.money macro is deprecated, use ActiveRecord::Base.attr_money macro. +* Currency::Exchange is now Currency::Exchange::Rate::Source + NOTE: Currency::Exchange::* is reserved for buying/selling currencies, not for providing rate data. +* Refactored xe.com homepage rate source as a Currency::Exchange::Rate::Source::Xe. +* Refactored Currency::Exchange::Test as Currency::Exchange::Rate::Source::Test. +* Support for historical money values and rates using ActiveRecord. +* Added Rate::Source::Historical::Writer. +* Added newyorkfed.org XML rate source. +* Added thefinancials.com XML rate source. +* Refactored rate deriviation into Currency::Exchange::Rate::Deriver. +* Refactored rate caching into Currency::Exchange::Rate::Source::TimedCache. +* Added Money attribute macros for classes not using ActiveRecord. +* Refactored time-based rate caching into Currency::Exchange::Rate::Source::TimedCache. +* Refactored Currency::Currency#format into Currency::Formatter. + NOTE: old formatting options as :no_* no longer supported. +* Refactored Currency::Currency#parse into Currency::Parser. +* Currency::CurrencyFactory is now Currency::Currency::Factory. +* Preliminary Currency::Exchange::Rate::Source::Failover. +* Added copyright notices: LICENSE.txt, COPYING.txt. + +== Release 0.3.3: 2006/10/31 + +* Inclusion of README.txt and Releases.txt into documentation. + +== Release 0.3.2: 2006/10/31 + +* BOO! +* Added expiration of rates in Xe. +* Fixed Currency.symbol formatting when Currency.symbol.nil? +* Added more Money tests. + +== Release 0.3.1: 2006/10/31 + +* Remove debug puts. + +== Release 0.3.0: 2006/10/31 + +* ActiveRecord money :*_field options are now named :*_column. +* More ActiveRecord tests + +== Release 0.2.1: 2006/10/31 + +* Fixed Manifest.txt + +== Release 0.2.0: 2006/10/31 + +* Restructured namespace +* Added more documentation +* Added ActiveRecord tests + +== Release 0.1.2: 2006/10/30 + +* Rakefile now uses Hoe + +== Release 0.1.1: 2006/10/30 + +* Fixes gem packaging errors. + +== Release 0.1.0: 2006/10/29 + +* Initial Release + diff --git a/TODO.txt b/TODO.txt new file mode 100644 index 0000000..f326c6a --- /dev/null +++ b/TODO.txt @@ -0,0 +1,9 @@ + += Currency To Do List + +* Clean up and normalize all exceptions: +** Rate sources should add :source => source, etc. +* Refactor all configuration class variables into Currency::Config +* Refactor all cached values into objects that can be reinstantiated on a per-thread basis +* Support http://www.xe.com/ucc/full.php rate queries. + diff --git a/bin/currency_historical_rate_load b/bin/currency_historical_rate_load new file mode 100755 index 0000000..1eb38a2 --- /dev/null +++ b/bin/currency_historical_rate_load @@ -0,0 +1,105 @@ +#!/usr/bin/env ruby +# -*- ruby -*- + +# Dependencies +bin_dir = File.dirname(__FILE__) +$:.unshift File.expand_path(bin_dir + "/../lib") + +require 'rubygems' + +gem 'activesupport' +gem 'activerecord' + +require 'active_record' + +require 'currency' +require 'currency/exchange/rate/source/historical/rate_loader' +require 'optparse' +require 'ostruct' +require 'yaml' + + +# Parse command line arguments. +opts = { } +opts[:db_config] = bin_dir + '/.db_config.yml' +opts[:rate_sources] = [ ] +opts[:required_currencies] = + [ + :USD, + :GBP, + :CAD, + :EUR, + ] +opts[:RAILS_ENV] = ENV["RAILS_ENV"] || 'development' + + +op = OptionParser.new do | op | + op.banner = "currency_historical_rate_load - loads currency rates from sources into historical rates table" + op.separator "Usage:" + op.on("--deploy-table", + TrueClass, + "If true the database table will be created." + ) do | v | + opts[:deploy_table] = v + end + op.on("-d", + "--db-config FILE", + String, + "The YAML file containing the ActiveRecord::Base database configuration." + ) do | v | + opts[:db_config] = v + end + op.on("-e", + "--rails-env ENV", + String, + "The configuration key to use from the --db-config file; default #{opts[:RAILS_ENV].inspect}." + ) do | v | + opts[:RAILS_ENV] = v + end + op.on("-s", + "--rate-source RATE_SOURCE", + String, + "The rate source to be queried." + ) do | v | + opts[:rate_sources] += v.split(/[\s,]+/) + end + op.on("-c", + "--currencies CURRENCY", + String, + "The required currencies; default: #{opts[:required_currencies].inspect}." + ) do | v | + opts[:required_currencies] = v.split(/[\s,]+/) + end + op.on("-h", + "--help", + "Show this message") do + STDERR.puts op.to_s + exit(1) + end +end + +args = ARGV.dup +op.parse!(args) + +# Setup the database environment. +db_config = File.open(opts[:db_config]) do | fh | + YAML::load(fh) +end +db_config.freeze +db_config = db_config[opts[:RAILS_ENV]] || raise("Cannot locate #{opts[:RAILS_ENV].inspect} in --db-config; available environments: #{db_config.keys.sort.inspect}") +db_config.freeze +ActiveRecord::Base.establish_connection(db_config) + +# Deploy table? +if opts[:deploy_table] + require 'active_record/migration' + Currency::Exchange::Rate::Source::Historical::Rate.__create_table(ActiveRecord::Migration) +end + +# Start Loading Rates. +instance = Currency::Exchange::Rate::Source::Historical::RateLoader.new(opts) +instance.run + +# Finished +exit(0) + diff --git a/examples/ex1.rb b/examples/ex1.rb new file mode 100644 index 0000000..4b6c697 --- /dev/null +++ b/examples/ex1.rb @@ -0,0 +1,13 @@ +$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) + +require 'currency' +require 'currency/exchange/rate/source/test' + +x = Currency.Money("1,203.43", :USD) + +puts x.to_s +puts (x * 10).to_s +puts (x * 33333).inspect + +puts x.currency.code.inspect + diff --git a/examples/xe1.rb b/examples/xe1.rb new file mode 100644 index 0000000..f4b7abd --- /dev/null +++ b/examples/xe1.rb @@ -0,0 +1,20 @@ +$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) + +require 'currency' +require 'currency/exchange/rate/source/xe' + +ex = Currency::Exchange::Rate::Source::Xe.new() +Currency::Exchange::Rate::Source.current = ex + +puts ex.inspect +puts ex.parse_page_rates.inspect + +usd = Currency.Money("1", 'USD') + +puts "usd = #{usd}" + +cad = usd.convert(:CAD) +puts "cad = #{cad}" + + + diff --git a/lib/currency.rb b/lib/currency.rb new file mode 100644 index 0000000..b4d9813 --- /dev/null +++ b/lib/currency.rb @@ -0,0 +1,143 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# +# See LICENSE.txt for details. +# +# = Currency +# +# The Currency package provides an object-oriented model of: +# +# * currencies +# * exchanges +# * exchange rates +# * exchange rate sources +# * monetary values +# +# The core classes are: +# +# * Currency::Money - uses a scaled integer representation of a monetary value and performs accurate conversions to and from string values. +# * Currency::Currency - provides an object-oriented representation of a currency. +# * Currency::Exchange::Base - the base class for a currency exchange rate provider. +# * Currency::Exchange::Rate::Source::Base - the base class for an on-demand currency exchange rate data provider. +# * Currency::Exchange::Rate::Source::Provider - the base class for a bulk exchange rate data provider. +# * Currency::Exchange::Rate - represents a exchange rate between two currencies. +# +# +# The example below uses Currency::Exchange::Xe to automatically get +# exchange rates from http://xe.com/ : +# +# require 'currency' +# require 'currency/exchange/rate/deriver' +# require 'currency/exchange/rate/source/xe' +# require 'currency/exchange/rate/source/timed_cache' +# +# # Rate source initialization +# provider = Currency::Exchange::Rate::Source::Xe.new +# deriver = Currency::Exchange::Rate::Deriver.new(:source => provider) +# cache = Currency::Exchange::Rate::Source::TimedCache.new(:source => deriver) +# Currency::Exchange::Rate::Source.default = cache +# +# usd = Currency::Money('6.78', :USD) +# puts "usd = #{usd.format}" +# cad = usd.convert(:CAD) +# puts "cad = #{cad.format}" +# +# == ActiveRecord Suppport +# +# This package also contains ActiveRecord support for money values: +# +# require 'currency' +# require 'currency/active_record' +# +# class Entry < ActiveRecord::Base +# money :amount +# end +# +# In the example above, the entries.amount database column is an INTEGER that represents US cents. +# The currency code of the money value can be stored in an additional database column or a default currency can be used. +# +# == Recent Enhancements +# +# === Storage and retrival of historical exchange rates +# +# * See Currency::Exchange::Rate::Source::Historical +# * See Currency::Exchange::Rate::Source::Historical::Writer +# +# === Automatic derivation of rates from base rates. +# +# * See Currency::Exchange::Rate::Deriver +# +# === Rate caching +# +# * See Currency::Exchange::Rate::Source::TimedCache +# +# === Rate Providers +# +# * See Currency::Exchange::Rate::Source::Xe +# * See Currency::Exchange::Rate::Source::NewYorkFed +# * See Currency::Exchange::Rate::Source::TheFinancials +# +# === Customizable formatting and parsing +# +# * See Currency::Formatter +# * See Currency::Parser +# +# == Future Enhancements +# +# * Support for inflationary rates within a currency, e.g. $10 USD in the year 1955 converted to 2006 USD. +# +# == SVN Repo +# +# svn checkout svn://rubyforge.org/var/svn/currency/currency/trunk +# +# == Examples +# +# See the examples/ and test/ directorys +# +# == Author +# +# Kurt Stephens http://kurtstephens.com +# +# == Support +# +# http://rubyforge.org/forum/forum.php?forum_id=7643 +# +# == Copyright +# +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# +# See LICENSE.txt for details. +# +module Currency + # Use this function instead of Money#new: + # + # Currency::Money("12.34", :CAD) + # + # Do not do this: + # + # Currency::Money.new("12.34", :CAD) + # + # See Money#new. + def self.Money(*opts) + Money.new(*opts) + end +end + +$:.unshift(File.expand_path(File.dirname(__FILE__))) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) + +require 'currency/currency_version' +require 'currency/config' +require 'currency/exception' +require 'currency/money' +require 'currency/currency' +require 'currency/currency/factory' +require 'currency/money' +require 'currency/formatter' +require 'currency/parser' +require 'currency/exchange' +require 'currency/exchange/rate' +require 'currency/exchange/rate/deriver' +require 'currency/exchange/rate/source' +require 'currency/exchange/rate/source/test' +require 'currency/exchange/time_quantitizer' +require 'currency/core_extensions' + diff --git a/lib/currency/active_record.rb b/lib/currency/active_record.rb new file mode 100644 index 0000000..a644ff1 --- /dev/null +++ b/lib/currency/active_record.rb @@ -0,0 +1,265 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'active_record/base' +require File.join(File.dirname(__FILE__), '..', 'currency') + +# See Currency::ActiveRecord::ClassMethods +class ActiveRecord::Base + @@money_attributes = { } + + # Called by money macro when a money attribute + # is created. + def self.register_money_attribute(attr_opts) + (@@money_attributes[attr_opts[:class]] ||= { })[attr_opts[:attr_name]] = attr_opts + end + + # Returns an array of option hashes for all the money attributes of + # this class. + # + # Superclass attributes are not included. + def self.money_attributes_for_class(cls) + (@@money_atttributes[cls] || { }).values + end + + + # Iterates through all known money attributes in all classes. + # + # each_money_attribute { | money_opts | + # ... + # } + def self.each_money_attribute(&blk) + @@money_attributes.each do | cls, hash | + hash.each do | attr_name, attr_opts | + yield attr_opts + end + end + end + +end # class + + +# See Currency::ActiveRecord::ClassMethods +module Currency::ActiveRecord + + def self.append_features(base) # :nodoc: + # $stderr.puts " Currency::ActiveRecord#append_features(#{base})" + super + base.extend(ClassMethods) + end + + + +# == ActiveRecord Suppport +# +# Support for Money attributes in ActiveRecord::Base subclasses: +# +# require 'currency' +# require 'currency/active_record' +# +# class Entry < ActiveRecord::Base +# attr_money :amount +# end +# + module ClassMethods + + # Deprecated: use attr_money. + def money(*args) + $stderr.puts "WARNING: money(#{args.inspect}) deprecated, use attr_money: in #{caller(1)[0]}" + attr_money(*args) + end + + + # Defines a Money object attribute that is bound + # to a database column. The database column to store the + # Money value representation is assumed to be + # INTEGER and will store Money#rep values. + # + # Options: + # + # :column => undef + # + # Defines the column to use for storing the money value. + # Defaults to the attribute name. + # + # If this column is different from the attribute name, + # the money object will intercept column=(x) to flush + # any cached Money object. + # + # :currency => currency_code (e.g.: :USD) + # + # Defines the Currency to use for storing a normalized Money + # value. + # + # All Money values will be converted to this Currency before + # storing. This allows SQL summary operations, + # like SUM(), MAX(), AVG(), etc., to produce meaningful results, + # regardless of the initial currency specified. If this + # option is used, subsequent reads will be in the specified + # normalization :currency. + # + # :currency_column => undef + # + # Defines the name of the CHAR(3) column used to store and + # retrieve the Money's Currency code. If this option is used, each + # record may use a different Currency to store the result, such + # that SQL summary operations, like SUM(), MAX(), AVG(), + # may return meaningless results. + # + # :currency_preferred_column => undef + # + # Defines the name of a CHAR(3) column used to store and + # retrieve the Money's Currency code. This option can be used + # with normalized Money values to retrieve the Money value + # in its original Currency, while + # allowing SQL summary operations on the normalized Money values + # to still be valid. + # + # :time => undef + # + # Defines the name of attribute used to + # retrieve the Money's time. If this option is used, each + # Money value will use this attribute during historical Currency + # conversions. + # + # Money values can share a time value with other attributes + # (e.g. a created_on column). + # + # If this option is true, the money time attribute will be named + # "#{attr_name}_time" and :time_update will be true. + # + # :time_update => undef + # + # If true, the Money time value is updated upon setting the + # money attribute. + # + def attr_money(attr_name, *opts) + opts = Hash[*opts] + + attr_name = attr_name.to_s + opts[:class] = self + opts[:table] = self.table_name + opts[:attr_name] = attr_name.intern + ::ActiveRecord::Base.register_money_attribute(opts) + + column = opts[:column] || opts[:attr_name] + opts[:column] = column + + if column.to_s != attr_name.to_s + alias_accessor = <<-"end_eval" +alias :before_money_#{column}=, :#{column}= + +def #{column}=(__value) + @{attr_name} = nil # uncache + before_money#{column} = __value +end + +end_eval + end + + currency = opts[:currency] + + currency_column = opts[:currency_column] + if currency_column && ! currency_column.kind_of?(String) + currency_column = currency_column.to_s + currency_column = "#{column}_currency" + end + if currency_column + read_currency = "read_attribute(:#{currency_column.to_s})" + write_currency = "write_attribute(:#{currency_column}, #{attr_name}_money.nil? ? nil : #{attr_name}_money.currency.code.to_s)" + end + opts[:currency_column] = currency_column + + currency_preferred_column = opts[:currency_preferred_column] + if currency_preferred_column + currency_preferred_column = currency_preferred_column.to_s + read_preferred_currency = "@#{attr_name} = @#{attr_name}.convert(read_attribute(:#{currency_preferred_column}))" + write_preferred_currency = "write_attribute(:#{currency_preferred_column}, @#{attr_name}_money.currency.code)" + end + + time = opts[:time] + write_time = '' + if time + if time == true + time = "#{attr_name}_time" + opts[:time_update] = true + end + read_time = "self.#{time}" + end + opts[:time] = time + if opts[:time_update] + write_time = "self.#{time} = #{attr_name}_money && #{attr_name}_money.time" + end + + currency ||= ':USD' + time ||= 'nil' + + read_currency ||= currency + read_time ||= time + + money_rep ||= "#{attr_name}_money.rep" + + validate_allow_nil = opts[:allow_nil] ? ', :allow_nil => true' : '' + validate = "# Validation\n" + validate << "\nvalidates_numericality_of :#{attr_name}#{validate_allow_nil}\n" + validate << "\nvalidates_format_of :#{currency_column}, :with => /^[A-Z][A-Z][A-Z]$/#{validate_allow_nil}\n" if currency_column + + + alias_accessor ||= '' + + module_eval (opts[:module_eval] = x = <<-"end_eval"), __FILE__, __LINE__ +#{validate} + +#{alias_accessor} + +def #{attr_name} + # $stderr.puts " \#{self.class.name}##{attr_name}" + unless @#{attr_name} + #{attr_name}_rep = read_attribute(:#{column}) + unless #{attr_name}_rep.nil? + @#{attr_name} = ::Currency::Money.new_rep(#{attr_name}_rep, #{read_currency} || #{currency}, #{read_time} || #{time}) + #{read_preferred_currency} + end + end + @#{attr_name} +end + +def #{attr_name}=(value) + if value.nil? + #{attr_name}_money = nil + elsif value.kind_of?(Integer) || value.kind_of?(String) || value.kind_of?(Float) + #{attr_name}_money = ::Currency::Money(value, #{currency}) + #{write_preferred_currency} + elsif value.kind_of?(::Currency::Money) + #{attr_name}_money = value + #{write_preferred_currency} + #{write_currency ? write_currency : "#{attr_name}_money = #{attr_name}_money.convert(#{currency})"} + else + raise ::Currency::Exception::InvalidMoneyValue, value + end + + @#{attr_name} = #{attr_name}_money + + write_attribute(:#{column}, #{attr_name}_money.nil? ? nil : #{money_rep}) + #{write_time} + + value +end + +def #{attr_name}_before_type_cast + # FIXME: User cannot specify Currency + x = #{attr_name} + x &&= x.format(:symbol => false, :currency => false, :thousands => false) + x +end + +end_eval + # $stderr.puts " CODE = #{x}" + end + end +end + + +ActiveRecord::Base.class_eval do + include Currency::ActiveRecord +end diff --git a/lib/currency/config.rb b/lib/currency/config.rb new file mode 100644 index 0000000..afc4134 --- /dev/null +++ b/lib/currency/config.rb @@ -0,0 +1,91 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +# The Currency::Config class is responsible for +# maintaining global configuration for the Currency package. +# +# TO DO: +# +# Migrate all class variable configurations to this object. +class Currency::Config + @@default = nil + + # Returns the default Currency::Config object. + # + # If one is not specfied an instance is + # created. This is a global, not thread-local. + def self.default + @@default ||= + self.new + end + + # Sets the default Currency::Config object. + def self.default=(x) + @@default = x + end + + # Returns the current Currency::Config object used during + # in the current thread. + # + # If #current= has not been called and #default= has not been called, + # then UndefinedExchange is raised. + def self.current + Thread.current[:Currency__Config] ||= + self.default || + (raise ::Currency::Exception::UndefinedConfig, "Currency::Config.default not defined") + end + + # Sets the current Currency::Config object used + # in the current thread. + def self.current=(x) + Thread.current[:Currency__Config] = x + end + + # Clones the current configuration and makes it current + # during the execution of a block. After block completes, + # the previous configuration is restored. + # + # Currency::Config.configure do | c | + # c.float_ref_filter = Proc.new { | x | x.round } + # "123.448".money.rep == 12345 + # end + def self.configure(&blk) + c_prev = current + c_new = self.current = current.clone + result = nil + begin + result = yield c_new + ensure + self.current = c_prev + end + result + end + + + @@identity = Proc.new { |x| x } # :nodoc: + + # Returns the current Float conversion filter. + # Can be used to set rounding or truncation policies when converting + # Float values to Money values. + # Defaults to an identity function. + # See Float#Money_rep. + def float_ref_filter + @float_ref_filter ||= + @@identity + end + + # Sets the current Float conversion filter. + def float_ref_filter=(x) + @float_ref_filter = x + end + + + # Defines the table name for Historical::Rate records. + # Defaults to 'currency_historical_rates'. + attr_accessor :historical_table_name + def historical_table_name + @historical_table_name ||= 'currency_historical_rates' + end + +end # module + diff --git a/lib/currency/core_extensions.rb b/lib/currency/core_extensions.rb new file mode 100644 index 0000000..3b42015 --- /dev/null +++ b/lib/currency/core_extensions.rb @@ -0,0 +1,41 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + + + +class Object + # Exact conversion to Money representation value. + def money(*opts) + Currency::Money(self, *opts) + end +end + + + +class Integer + # Exact conversion to Money representation value. + def Money_rep(currency, time = nil) + Integer(self * currency.scale) + end +end + + + +class Float + # Inexact conversion to Money representation value. + def Money_rep(currency, time = nil) + Integer(Currency::Config.current.float_ref_filter.call(self * currency.scale)) + end +end + + + +class String + # Exact conversion to Money representation value. + def Money_rep(currency, time = nil) + x = currency.parse(self, :currency => currency, :time => time) + x = x.rep if x.respond_to?(:rep) + x + end +end + diff --git a/lib/currency/currency.rb b/lib/currency/currency.rb new file mode 100644 index 0000000..fed1233 --- /dev/null +++ b/lib/currency/currency.rb @@ -0,0 +1,175 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + + +# Represents a currency. +# +# Currency objects are created on-demand by Currency::Currency::Factory. +# +# See Currency.get method. +# +class Currency::Currency + # Returns the ISO three-letter currency code as a symbol. + # e.g. :USD, :CAD, etc. + attr_reader :code + + # The Currency's scale factor. + # e.g: the :USD scale factor is 100. + attr_reader :scale + + # The Currency's scale factor. + # e.g: the :USD scale factor is 2, where 10 ^ 2 == 100. + attr_reader :scale_exp + + # Used by Formatter. + attr_reader :format_right + + # Used by Formatter. + attr_reader :format_left + + # The Currency's symbol. + # e.g: USD symbol is '$' + attr_accessor :symbol + + # The Currency's symbol as HTML. + # e.g: EUR symbol is '&#8364;' (:html &#8364; :) or '&euro;' (:html &euro; :) + attr_accessor :symbol_html + + # The default Formatter. + attr_accessor :formatter + + # The default parser. + attr_accessor :parser + + + # Create a new currency. + # This should only be called from Currency::Currency::Factory. + def initialize(code, symbol = nil, scale = 10000) + self.code = code + self.symbol = symbol + self.scale = scale + + @formatter = + @parser = + nil + end + + + # Returns the Currency object from the default Currency::Currency::Factory + # by its three-letter uppercase Symbol, such as :USD, or :CAD. + def self.get(code) + # $stderr.puts "#{self}.get(#{code.inspect})" + return nil unless code + return code if code.kind_of?(::Currency::Currency) + Factory.default.get_by_code(code) + end + + + # Internal method for converting currency codes to internal + # Symbol format. + def self.cast_code(x) + x = x.upcase.intern if x.kind_of?(String) + raise ::Currency::Exception::InvalidCurrencyCode, x unless x.kind_of?(Symbol) + raise ::Currency::Exception::InvalidCurrencyCode, x unless x.to_s.length == 3 + x + end + + + # Returns the hash of the Currency's code. + def hash + @code.hash + end + + + # Returns true if the Currency's are equal. + def eql?(x) + self.class == x.class && @code == x.code + end + + + # Returns true if the Currency's are equal. + def ==(x) + self.class == x.class && @code == x.code + end + + + # Clients should never call this directly. + def code=(x) + x = self.class.cast_code(x) unless x.nil? + @code = x + #$stderr.puts "#{self}.code = #{@code}"; x + end + + + # Clients should never call this directly. + def scale=(x) + @scale = x + return x if x.nil? + @scale_exp = Integer(Math.log10(@scale)); + @format_right = - @scale_exp + @format_left = @format_right - 1 + x + end + + + # Parse a Money string in this Currency. + # + # See Currency::Parser#parse. + # + def parse(str, *opt) + parser_or_default.parse(str, *opt) + end + + + def parser_or_default + (@parser || ::Currency::Parser.default) + end + + + # Formats the Money value as a string using the current Formatter. + # See Currency::Formatter#format. + def format(m, *opt) + formatter_or_default.format(m, *opt) + end + + + def formatter_or_default + (@formatter || ::Currency::Formatter.default) + end + + + # Returns the Currency code as a String. + def to_s + @code.to_s + end + + + # Returns the default Factory's currency. + def self.default + Factory.default.currency + end + + + # Sets the default Factory's currency. + def self.default=(x) + x = self.get(x) unless x.kind_of?(self) + Factory.default.currency = x + end + + + # If selector is [A-Z][A-Z][A-Z], load the currency via Factory.default. + # + # Currency::Currency.USD + # => #<Currency::Currency:0xb7d0917c @formatter=nil, @scale_exp=2, @scale=100, @symbol="$", @format_left=-3, @code=:USD, @parser=nil, @format_right=-2> + # + def self.method_missing(sel, *args, &blk) + if args.size == 0 && (! block_given?) && /^[A-Z][A-Z][A-Z]$/.match(sel.to_s) + Factory.default.get_by_code(sel) + else + super + end + end + +end # class + + diff --git a/lib/currency/currency/factory.rb b/lib/currency/currency/factory.rb new file mode 100644 index 0000000..3215d1f --- /dev/null +++ b/lib/currency/currency/factory.rb @@ -0,0 +1,121 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + + +# Responsible for creating Currency::Currency objects on-demand. +class Currency::Currency::Factory + @@default = nil + + # Returns the default Currency::Factory. + def self.default + @@default ||= self.new + end + # Sets the default Currency::Factory. + def self.default=(x) + @@default = x + end + + + def initialize(*opts) + @currency_by_code = { } + @currency_by_symbol = { } + @currency = nil + end + + + # Lookup Currency by code. + def get_by_code(x) + x = ::Currency::Currency.cast_code(x) + # $stderr.puts "get_by_code(#{x})" + @currency_by_code[x] ||= install(load(::Currency::Currency.new(x))) + end + + + # Lookup Currency by symbol. + def get_by_symbol(symbol) + @currency_by_symbol[symbol] ||= install(load(::Currency::Currency.new(nil, symbol))) + end + + + # This method initializes a Currency object as + # requested from #get_by_code or #get_by_symbol. + # + # This method must initialize: + # + # currency.code + # currency.scale + # + # Optionally: + # + # currency.symbol + # currency.symbol_html + # + # Subclasses that provide Currency metadata should override this method. + # For example, loading Currency metadata from a database or YAML file. + def load(currency) + # $stderr.puts "BEFORE: load(#{currency.code})" + + # Basic + if currency.code == :USD || currency.symbol == '$' + # $stderr.puts "load('USD')" + currency.code = :USD + currency.symbol = '$' + currency.scale = 10000 + elsif currency.code == :CAD + # $stderr.puts "load('CAD')" + currency.symbol = '$' + currency.scale = 10000 + elsif currency.code == :EUR + # $stderr.puts "load('CAD')" + currency.symbol = nil + currency.symbol_html = '&#8364;' + currency.scale = 10000 + else + currency.symbol = nil + currency.scale = 10000 + end + + # $stderr.puts "AFTER: load(#{currency.inspect})" + + currency + end + + + # Installs a new Currency for #get_by_symbol and #get_by_code. + def install(currency) + raise ::Currency::Exception::UnknownCurrency unless currency + @currency_by_symbol[currency.symbol] ||= currency unless currency.symbol.nil? + @currency_by_code[currency.code] = currency + end + + + # Returns the default Currency. + # Defaults to self.get_by_code(:USD). + def currency + @currency ||= self.get_by_code(:USD) + end + + + # Sets the default Currency. + def currency=(x) + @currency = x + end + + + # If selector is [A-Z][A-Z][A-Z], load the currency. + # + # factory.USD + # => #<Currency::Currency:0xb7d0917c @formatter=nil, @scale_exp=2, @scale=100, @symbol="$", @format_left=-3, @code=:USD, @parser=nil, @format_right=-2> + # + def method_missing(sel, *args, &blk) + if args.size == 0 && (! block_given?) && /^[A-Z][A-Z][A-Z]$/.match(sel.to_s) + self.get_by_code(sel) + else + super + end + end + +end # class + + + diff --git a/lib/currency/currency_version.rb b/lib/currency/currency_version.rb new file mode 100644 index 0000000..1d3c9d0 --- /dev/null +++ b/lib/currency/currency_version.rb @@ -0,0 +1,6 @@ +module Currency + CurrencyVersion = '0.4.11' +end +# DO NOT EDIT +# This file is auto-generated by build scripts. +# See: rake update_version diff --git a/lib/currency/exception.rb b/lib/currency/exception.rb new file mode 100644 index 0000000..9fdedfd --- /dev/null +++ b/lib/currency/exception.rb @@ -0,0 +1,119 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +module Currency::Exception + # Base class for all Currency::Exception objects. + # + # raise Currency::Exception [ "msg", :opt1, 1, :opt2, 2 ] + # + class Base < ::Exception + EMPTY_HASH = { }.freeze + + def initialize(arg1, *args) + case arg1 + # [ description, ... ] + when Array + @opts = arg1 + arg1 = arg1.shift + else + @opts = nil + end + + case @opts + when Array + if @opts.size == 1 && @opts.first.kind_of?(Hash) + # [ description, { ... } ] + @opts = @opts.first + else + # [ description, :key, value, ... ] + @opts = Hash[*@opts] + end + end + + case @opts + when Hash + @opts = @opts.dup.freeze + else + @opts = { :info => @opts }.freeze + end + + @opts ||= EMPTY_HASH + + super(arg1, *args) + end + + + def method_missing(sel, *args, &blk) + sel = sel.to_sym + if args.empty? && ! block_given? && @opts.key?(sel) + return @opts[sel] + end + super + end + + def to_s + super + ": #{@opts.inspect}" + end + + end + + # Generic Error. + class Generic < Base + end + + # Error during parsing of Money values from String. + class InvalidMoneyString < Base + end + + # Error during coercion of external Money values. + class InvalidMoneyValue < Base + end + + # Error in Currency code formeat. + class InvalidCurrencyCode < Base + end + + # Error during conversion between currencies. + class IncompatibleCurrency < Base + end + + # Error during locating currencies. + class MissingCurrency < Base + end + + # Error if an Exchange is not defined. + class UndefinedExchange < Base + end + + # Error if a Currency is unknown. + class UnknownCurrency < Base + end + + # Error if an Exchange Rate Source cannot provide an Exchange::Rate. + class UnknownRate < Base + end + + # Error if an Exchange Rate Source. + class RateSourceError < Base + end + + # Error if an Exchange Rate Source cannot supply any rates. + class UnavailableRates < Base + end + + # Error if an Exchange::Rate is not valid. + class InvalidRate < Base + end + + # Error if a subclass is responsible for implementing a method. + class SubclassResponsibility < Base + end + + # Error if some functionality is unimplemented + class Unimplemented < Base + end + + # Error if reentrantancy is d + class InvalidReentrancy < Base + end +end # module diff --git a/lib/currency/exchange.rb b/lib/currency/exchange.rb new file mode 100644 index 0000000..03550bf --- /dev/null +++ b/lib/currency/exchange.rb @@ -0,0 +1,50 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency' + +# The Currency::Exchange package is responsible for +# the buying and selling of currencies. +# +# This feature is currently unimplemented. +# +# Exchange rate sources are configured via Currency::Exchange::Rate::Source. +# +module Currency::Exchange + @@default = nil + @@current = nil + + # Returns the default Currency::Exchange object. + # + # If one is not specfied an instance of Currency::Exchange::Base is + # created. Currency::Exchange::Base cannot service any + # conversion rate requests. + def self.default + @@default ||= raise :Currency::Exception::Unimplemented, :default + end + + # Sets the default Currency::Exchange object. + def self.default=(x) + @@default = x + end + + # Returns the current Currency::Exchange object used during + # explicit and implicit Money trading. + # + # If #current= has not been called and #default= has not been called, + # then UndefinedExchange is raised. + def self.current + @@current || self.default || (raise ::Currency::Exception::UndefinedExchange, "Currency::Exchange.current not defined") + end + + # Sets the current Currency::Exchange object used during + # explicit and implicit Money conversions. + def self.current=(x) + @@current = x + end + +end # module + +require 'currency/exchange/rate' +require 'currency/exchange/rate/source' + diff --git a/lib/currency/exchange/rate.rb b/lib/currency/exchange/rate.rb new file mode 100644 index 0000000..516a39e --- /dev/null +++ b/lib/currency/exchange/rate.rb @@ -0,0 +1,214 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange' + +# Represents a convertion rate between two currencies at a given period of time. +class Currency::Exchange::Rate + # The first Currency. + attr_reader :c1 + + # The second Currency. + attr_reader :c2 + + # The rate between c1 and c2. + # + # To convert between m1 in c1 and m2 in c2: + # + # m2 = m1 * rate. + attr_reader :rate + + # The source of the rate. + attr_reader :source + + # The Time of the rate. + attr_reader :date + + # If the rate is derived from other rates, this describes from where it was derived. + attr_reader :derived + + # Average rate over rate samples in a time range. + attr_reader :rate_avg + + # Number of rate samples used to calcuate _rate_avg_. + attr_reader :rate_samples + + # The rate low between date_0 and date_1. + attr_reader :rate_lo + + # The rate high between date_0 and date_1. + attr_reader :rate_hi + + # The rate at date_0. + attr_reader :rate_date_0 + + # The rate at date_1. + attr_reader :rate_date_1 + + # The lowest date of sampled rates. + attr_reader :date_0 + + # The highest date of sampled rates. + # This is non-inclusive during searches to allow seamless tileings of + # time with rate buckets. + attr_reader :date_1 + + def initialize(c1, c2, c1_to_c2_rate, source = "UNKNOWN", date = nil, derived = nil, reciprocal = nil, opts = nil) + @c1 = c1 + @c2 = c2 + @rate = c1_to_c2_rate + raise ::Currency::Exception::InvalidRate, + [ + "rate is not positive", + :rate, @rate, + :c1, c1, + :c2, c2, + ] unless @rate && @rate >= 0.0 + @source = source + @date = date + @derived = derived + @reciprocal = reciprocal + + # + @rate_avg = + @rate_samples = + @rate_lo = + @rate_hi = + @rate_date_0 = + @rate_date_1 = + @date_0 = + @date_1 = + nil + + if opts + opts.each_pair do | k, v | + self.instance_variable_set("@#{k}", v) + end + end + end + + + # Returns a cached reciprocal Rate object from c2 to c1. + def reciprocal + @reciprocal ||= @rate == 1.0 ? self : + self.class.new(@c2, @c1, + 1.0 / @rate, + @source, + @date, + "reciprocal(#{derived || "#{c1.code}#{c2.code}"})", self, + { + :rate_avg => @rate_avg && 1.0 / @rate_avg, + :rate_samples => @rate_samples, + :rate_lo => @rate_lo && 1.0 / @rate_lo, + :rate_hi => @rate_hi && 1.0 / @rate_hi, + :rate_date_0 => @rate_date_0 && 1.0 / @rate_date_0, + :rate_date_1 => @rate_date_1 && 1.0 / @rate_date_1, + :date_0 => @date_0, + :date_1 => @date_1, + } + ) + end + + + # Converts from _m_ in Currency _c1_ to the opposite currency. + def convert(m, c1) + m = m.to_f + if @c1 == c1 + # $stderr.puts "Converting #{@c1} #{m} to #{@c2} #{m * @rate} using #{@rate}" + m * @rate + else + # $stderr.puts "Converting #{@c2} #{m} to #{@c1} #{m / @rate} using #{1.0 / @rate}; recip" + m / @rate + end + end + + + # Collect rate samples into rate_avg, rate_hi, rate_lo, rate_date_0, rate_date_1, date_0, date_1. + def collect_rates(rates) + rates = [ rates ] unless rates.kind_of?(Enumerable) + rates.each do | r | + collect_rate(r) + end + self + end + + # Collect rates samples in to this Rate. + def collect_rate(rate) + # Initial. + @rate_samples ||= 0 + @rate_sum ||= 0 + @source ||= rate.source + @c1 ||= rate.c1 + @c2 ||= rate.c2 + + # Reciprocal? + if @c1 == rate.c2 && @c2 == rate.c1 + collect_rate(rate.reciprocal) + elsif ! (@c1 == rate.c1 && @c2 == rate.c2) + raise ::Currency::Exception::InvalidRate, + [ + "Cannot collect rates between different currency pairs", + :rate1, self, + :rate2, rate, + ] + else + # Multisource? + @source = "<<multiple-sources>>" unless @source == rate.source + + # Calculate rate average. + @rate_samples += 1 + @rate_sum += rate.rate || (rate.rate_lo + rate.rate_hi) * 0.5 + @rate_avg = @rate_sum / @rate_samples + + # Calculate rates ranges. + r = rate.rate_lo || rate.rate + unless @rate_lo && @rate_lo < r + @rate_lo = r + end + r = rate.rate_hi || rate.rate + unless @rate_hi && @rate_hi > r + @rate_hi = r + end + + # Calculate rates on date range boundaries + r = rate.rate_date_0 || rate.rate + d = rate.date_0 || rate.date + unless @date_0 && @date_0 < d + @date_0 = d + @rate_date_0 = r + end + + r = rate.rate_date_1 || rate.rate + d = rate.date_1 || rate.date + unless @date_1 && @date_1 > d + @date_1 = d + @rate_date_1 = r + end + + @date ||= rate.date || rate.date0 || rate.date1 + end + self + end + + + def to_s(extended = false) + extended = "#{date_0} #{rate_date_0} |< #{rate_lo} #{rate} #{rate_hi} >| #{rate_date_1} #{date_1}" if extended + extended ||= '' + "#<#{self.class.name} #{c1.code} #{c2.code} #{rate} #{source.inspect} #{date ? date.strftime('%Y/%m/%d-%H:%M:%S') : 'nil'} #{derived && derived.inspect} #{extended}>" + end + + def inspect; to_s; end + +end # class + + +class Currency::Exchange::Rate::Writable < Currency::Exchange::Rate + attr_writer :source + attr_writer :derived + attr_writer :rate + def initialize(c1 = nil, c2 = nil, rate = nil, *opts) + super(c1, c2, 0.0, *opts) + @rate = rate + end +end # class + diff --git a/lib/currency/exchange/rate/deriver.rb b/lib/currency/exchange/rate/deriver.rb new file mode 100644 index 0000000..d155560 --- /dev/null +++ b/lib/currency/exchange/rate/deriver.rb @@ -0,0 +1,157 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate' +require 'currency/exchange/rate/source/base' + +# The Currency::Exchange::Rate::Deriver class calculates derived rates +# from base Rates from a rate Source by pivoting against a pivot currency or by +# generating reciprocals. +# +class Currency::Exchange::Rate::Deriver < Currency::Exchange::Rate::Source::Base + + # The source for base rates. + attr_accessor :source + + + def name + source.name + end + + + def initialize(opt = { }) + @source = nil + @pivot_currency = nil + @derived_rates = { } + @all_rates = { } + super + end + + + def pivot_currency + @pivot_currency || @source.pivot_currency || :USD + end + + + # Return all currencies. + def currencies + @source.currencies + end + + + # Flush all cached Rates. + def clear_rates + @derived_rates.clear + @all_rates.clear + @source.clear_rates + super + end + + + # Returns all combinations of rates except identity rates. + def rates(time = nil) + time = time && normalize_time(time) + all_rates(time) + end + + + # Computes all rates. + # time is assumed to be normalized. + def all_rates(time = nil) + if x = @all_rates["#{time}"] + return x + end + + x = @all_rates["#{time}"] = [ ] + + currencies = self.currencies + + currencies.each do | c1 | + currencies.each do | c2 | + next if c1 == c2 + c1 = ::Currency::Currency.get(c1) + c2 = ::Currency::Currency.get(c2) + rate = rate(c1, c2, time) + x << rate + end + end + + x + end + + + # Determines and creates the Rate between Currency c1 and c2. + # + # May attempt to use a pivot currency to bridge between + # rates. + # + def get_rate(c1, c2, time) + rate = get_rate_reciprocal(c1, c2, time) + + # Attempt to use pivot_currency to bridge + # between Rates. + unless rate + pc = ::Currency::Currency.get(pivot_currency) + + if pc && + (rate_1 = get_rate_reciprocal(c1, pc, time)) && + (rate_2 = get_rate_reciprocal(pc, c2, time)) + c1_to_c2_rate = rate_1.rate * rate_2.rate + rate = new_rate(c1, c2, + c1_to_c2_rate, + rate_1.date || rate_2.date || time, + "pivot(#{pc.code},#{rate_1.derived || "#{rate_1.c1.code}#{rate_1.c2.code}"},#{rate_2.derived || "#{rate_2.c1}#{rate_2.c2}"})") + end + end + + rate + end + + + # Get a matching base rate or its reciprocal. + def get_rate_reciprocal(c1, c2, time) + rate = get_rate_base_cached(c1, c2, time) + unless rate + if rate = get_rate_base_cached(c2, c1, time) + rate = (@rate["#{c1}:#{c2}:#{time}"] ||= rate.reciprocal) + end + end + + rate + end + + + # Returns a cached base Rate. + # + def get_rate_base_cached(c1, c2, time) + rate = (@rate["#{c1}:#{c2}:#{time}"] ||= get_rate_base(c1, c2, time)) + rate + end + + + # Returns a base Rate from the Source. + def get_rate_base(c1, c2, time) + if c1 == c2 + # Identity rates are timeless. + new_rate(c1, c2, 1.0, nil, "identity") + else + source.rate(c1, c2, time) + end + end + + + def load_rates(time = nil) + all_rates(time) + end + + + # Returns true if the underlying rate provider is available. + def available?(time = nil) + source.available?(time) + end + + +end # class + + + diff --git a/lib/currency/exchange/rate/source.rb b/lib/currency/exchange/rate/source.rb new file mode 100644 index 0000000..fea50ea --- /dev/null +++ b/lib/currency/exchange/rate/source.rb @@ -0,0 +1,89 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate' + +# +# The Currency::Exchange::Rate::Source package is responsible for +# providing rates between currencies at a given time. +# +# It is not responsible for purchasing or selling actual money. +# See Currency::Exchange. +# +# Currency::Exchange::Rate::Source::Provider subclasses are true rate data +# providers. See the #load_rates method. They provide groups of rates +# at a given time. +# +# Other Currency::Exchange::Rate::Source::Base subclasses +# are chained to provide additional rate source behavior, +# such as caching and derived rates. They provide individual rates between +# currencies at a given time. See the #rate method. An application +# will interface directly to a Currency::Exchange::Rate::Source::Base. +# A rate aggregator like Currency::Exchange::Rate::Historical::Writer will +# interface directly to a Currency::Exchange::Rate::Source::Provider. +# +# == IMPORTANT +# +# Rates sources should *never* install themselves +# as a Currency::Exchange::Rate::Source.current or +# Currency::Exchange::Rate::Source.default. The application itself is +# responsible setting up the default rate source. +# The old auto-installation behavior of rate sources, +# like Currency::Exchange::Xe, is no longer supported. +# +# == Initialization of Rate Sources +# +# A typical application will use the following rate source chain: +# +# * Currency::Exchange::Rate::Source::TimedCache +# * Currency::Exchange::Rate::Deriver +# * a Currency::Exchange::Rate::Source::Provider subclass, like Currency::Exchange::Rate::Source::Xe. +# +# Somewhere at initialization of application: +# +# require 'currency' +# require 'currency/exchange/rate/deriver' +# require 'currency/exchange/rate/source/xe' +# require 'currency/exchange/rate/source/timed_cache' +# +# provider = Currency::Exchange::Rate::Source::Xe.new +# deriver = Currency::Exchange::Rate::Deriver.new(:source => provider) +# cache = Currency::Exchange::Rate::Source::TimedCache.new(:source => deriver) +# Currency::Exchange::Rate::Source.default = cache +# +module Currency::Exchange::Rate::Source + + @@default = nil + @@current = nil + + # Returns the default Currency::Exchange::Rate::Source::Base object. + # + # If one is not specfied an instance of Currency::Exchange::Rate::Source::Base is + # created. Currency::Exchange::Rate::Source::Base cannot service any + # conversion rate requests. + def self.default + @@default ||= Base.new + end + + # Sets the default Currency::Exchange object. + def self.default=(x) + @@default = x + end + + # Returns the current Currency::Exchange object used during + # explicit and implicit Money conversions. + # + # If #current= has not been called and #default= has not been called, + # then UndefinedExchange is raised. + def self.current + @@current || self.default || (raise ::Currency::Exception::UndefinedExchange, "Currency::Exchange.current not defined") + end + + # Sets the current Currency::Exchange object used during + # explicit and implicit Money conversions. + def self.current=(x) + @@current = x + end +end + +require 'currency/exchange/rate/source/base' diff --git a/lib/currency/exchange/rate/source/base.rb b/lib/currency/exchange/rate/source/base.rb new file mode 100644 index 0000000..9472981 --- /dev/null +++ b/lib/currency/exchange/rate/source/base.rb @@ -0,0 +1,166 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source' + +# = Currency::Exchange::Rate::Source::Base +# +# The Currency::Exchange::Rate::Source::Base class is the base class for +# currency exchange rate providers. +# +# Currency::Exchange::Rate::Source::Base subclasses are Currency::Exchange::Rate +# factories. +# +# Represents a method of converting between two currencies. +# +# See Currency;:Exchange::Rate::source for more details. +# +class Currency::Exchange::Rate::Source::Base + + # The name of this Exchange. + attr_accessor :name + + # Currency to use as pivot for deriving rate pairs. + # Defaults to :USD. + attr_accessor :pivot_currency + + # If true, this Exchange will log information. + attr_accessor :verbose + + attr_accessor :time_quantitizer + + + def initialize(opt = { }) + @name = nil + @verbose = nil unless defined? @verbose + @pivot_currency ||= :USD + + @rate = { } + @currencies = nil + opt.each_pair{|k,v| self.send("#{k}=", v)} + end + + + def __subclass_responsibility(meth) + raise ::Currency::Exception::SubclassResponsibility, + [ + "#{self.class}#\#{meth}", + :class, self.class, + :method, method, + ] + end + + + # Converts Money m in Currency c1 to a new + # Money value in Currency c2. + def convert(m, c2, time = nil, c1 = nil) + c1 = m.currency if c1 == nil + time = m.time if time == nil + time = normalize_time(time) + if c1 == c2 && normalize_time(m.time) == time + m + else + rate = rate(c1, c2, time) + # raise ::Currency::Exception::UnknownRate, "#{c1} #{c2} #{time}" unless rate + + rate && ::Currency::Money(rate.convert(m, c1), c2, time) + end + end + + + # Flush all cached Rate. + def clear_rates + @rate.clear + @currencies = nil + end + + + # Flush any cached Rate between Currency c1 and c2. + def clear_rate(c1, c2, time, recip = true) + time = time && normalize_time(time) + @rate["#{c1}:#{c2}:#{time}"] = nil + @rate["#{c2}:#{c1}:#{time}"] = nil if recip + time + end + + + # Returns the cached Rate between Currency c1 and c2 at a given time. + # + # Time is normalized using #normalize_time(time) + # + # Subclasses can override this method to implement + # rate expiration rules. + # + def rate(c1, c2, time) + time = time && normalize_time(time) + @rate["#{c1}:#{c2}:#{time}"] ||= get_rate(c1, c2, time) + end + + + # Gets all rates available by this source. + # + def rates(time = nil) + __subclass_responsibility(:rates) + end + + + # Returns a list of Currencies that the rate source provides. + # + # Subclasses can override this method. + def currencies + @currencies ||= rates.collect{| r | [ r.c1, r.c2 ]}.flatten.uniq + end + + + # Determines and creates the Rate between Currency c1 and c2. + # + # May attempt to use a pivot currency to bridge between + # rates. + # + def get_rate(c1, c2, time) + __subclass_responsibility(:get_rate) + end + + # Returns a base Rate. + # + # Subclasses are required to implement this method. + def get_rate_base(c1, c2, time) + __subclass_responsibility(:get_rate_base) + end + + + # Returns a list of all available rates. + # + # Subclasses must override this method. + def get_rates(time = nil) + __subclass_responsibility(:get_rates) + end + + + # Called by implementors to construct new Rate objects. + def new_rate(c1, c2, c1_to_c2_rate, time = nil, derived = nil) + c1 = ::Currency::Currency.get(c1) + c2 = ::Currency::Currency.get(c2) + rate = ::Currency::Exchange::Rate.new(c1, c2, c1_to_c2_rate, name, time, derived) + # $stderr.puts "new_rate = #{rate}" + rate + end + + + # Normalizes rate time to a quantitized value. + # + # Subclasses can override this method. + def normalize_time(time) + time && (time_quantitizer || ::Currency::Exchange::TimeQuantitizer.current).quantitize_time(time) + end + + + # Returns a simple string rep. + def to_s + "#<#{self.class.name} #{self.name && self.name.inspect}>" + end + alias :inspect :to_s + +end # class + + diff --git a/lib/currency/exchange/rate/source/failover.rb b/lib/currency/exchange/rate/source/failover.rb new file mode 100644 index 0000000..85a2c3d --- /dev/null +++ b/lib/currency/exchange/rate/source/failover.rb @@ -0,0 +1,63 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source' + + +# Gets Rates from primary source, if primary fails, attempts secondary source. +# +class Currency::Exchange::Rate::Source::Failover < ::Currency::Exchange::Base + # Primary rate source. + attr_accessor :primary + + # Secondary rate source if primary fails. + attr_accessor :secondary + + def name + "failover(#{primary.name}, #{secondary.name})" + end + + + def clear_rates + @primary.clear_rates + @secondary.clear_rates + super + end + + + def get_rate(c1, c2, time) + rate = nil + + # Try primary. + err = nil + begin + rate = @primary.get_rate(c1, c2, time) + rescue Object => e + err = e + end + + + if rate == nil || err + $stderr.puts "Failover: primary failed for get_rate(#{c1}, #{c2}, #{time}) : #{err.inspect}" + rate = @secondary.get_rate(c1, c2, time) + end + + + unless rate + raise Currency::Exception::UnknownRate, + [ + "Failover: secondary failed for get_rate(#{c1}, #{c2}, #{time})", + :c1, c1, + :c2, c2, + :time, time, + ] + end + + rate + end + + +end # class + + + diff --git a/lib/currency/exchange/rate/source/federal_reserve.rb b/lib/currency/exchange/rate/source/federal_reserve.rb new file mode 100644 index 0000000..3696dab --- /dev/null +++ b/lib/currency/exchange/rate/source/federal_reserve.rb @@ -0,0 +1,160 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source/provider' + +require 'net/http' +require 'open-uri' + + +# Connects to http://www.federalreserve.gov/releases/H10/hist/dat00_<country>.txtb +# Parses all known currency files. +# +class Currency::Exchange::Rate::Source::FederalReserve < ::Currency::Exchange::Rate::Source::Provider + # Defines the pivot currency for http://www.federalreserve.gov/releases/H10/hist/dat00_#{country_code}.txt data files. + PIVOT_CURRENCY = :USD + + # Arbitrary currency code used by www.federalreserve.gov for + # naming historical data files. + # Used internally. + attr_accessor :country_code + + def initialize(*opt) + self.uri = 'http://www.federalreserve.gov/releases/H10/hist/dat00_#{country_code}.txt' + self.country_code = '' + @raw_rates = nil + super(*opt) + end + + + # Returns 'federalreserve.gov'. + def name + 'federalreserve.gov' + end + + + # FIXME? + #def available?(time = nil) + # time ||= Time.now + # ! [0, 6].include?(time.wday) ? true : false + #end + + + def clear_rates + @raw_rates = nil + super + end + + + def raw_rates + rates + @raw_rates + end + + # Maps bizzare federalreserve.gov country codes to ISO currency codes. + # May only work for the dat00_XX.txt data files. + # See http://www.jhall.demon.co.uk/currency/by_country.html + # + # Some data files list reciprocal rates! + @@country_to_currency = + { + 'al' => [ :AUD, :USD ], + # 'au' => :ASH, # AUSTRIAN SHILLING: pre-EUR? + 'bz' => [ :USD, :BRL ], + 'ca' => [ :USD, :CAD ], + 'ch' => [ :USD, :CNY ], + 'dn' => [ :USD, :DKK ], + 'eu' => [ :EUR, :USD ], + # 'gr' => :XXX, # Greece Drachma: pre-EUR? + 'hk' => [ :USD, :HKD ], + 'in' => [ :USD, :INR ], + 'ja' => [ :USD, :JPY ], + 'ma' => [ :USD, :MYR ], + 'mx' => [ :USD, :MXN ], # OR MXP? + 'nz' => [ :NZD, :USD ], + 'no' => [ :USD, :NOK ], + 'ko' => [ :USD, :KRW ], + 'sf' => [ :USD, :ZAR ], + 'sl' => [ :USD, :LKR ], + 'sd' => [ :USD, :SEK ], + 'sz' => [ :USD, :CHF ], + 'ta' => [ :USD, :TWD ], # New Taiwan Dollar. + 'th' => [ :USD, :THB ], + 'uk' => [ :GBP, :USD ], + 've' => [ :USD, :VEB ], + } + + + # Parses text file for rates. + def parse_rates(data = nil) + data = get_page_content unless data + + rates = [ ] + + @raw_rates ||= { } + + $stderr.puts "#{self}: parse_rates: data =\n#{data}" if @verbose + + # Rates are USD/currency so + # c1 = currency + # c2 = :USD + c1, c2 = @@country_to_currency[country_code] + + unless c1 && c2 + raise ::Currency::Exception::UnavailableRates, "Cannot determine currency code for federalreserve.gov country code #{country_code.inspect}" + end + + data.split(/\r?\n\r?/).each do | line | + # day month yy rate + m = /^\s*(\d\d?)-([A-Z][a-z][a-z])-(\d\d)\s+([\d\.]+)/.match(line) + next unless m + + day = m[1].to_i + month = m[2] + year = m[3].to_i + if year >= 50 and year < 100 + year += 1900 + elsif year < 50 + year += 2000 + end + + date = Time.parse("#{day}-#{month}-#{year} 12:00:00 -05:00") # USA NY => EST + + rate = m[4].to_f + + STDERR.puts "#{c1} #{c2} #{rate}\t#{date}" if @verbose + + rates << new_rate(c1, c2, rate, date) + + ((@raw_rates[date] ||= { })[c1] ||= { })[c2] ||= rate + ((@raw_rates[date] ||= { })[c2] ||= { })[c1] ||= 1.0 / rate + end + + # Put most recent rate first. + # See Provider#get_rate. + rates.reverse! + + # $stderr.puts "rates = #{rates.inspect}" + raise ::Currency::Exception::UnavailableRates, "No rates found in #{get_uri.inspect}" if rates.empty? + + rates + end + + + # Return a list of known base rates. + def load_rates(time = nil) + # $stderr.puts "#{self}: load_rates(#{time})" if @verbose + self.date = time + rates = [ ] + @@country_to_currency.keys.each do | cc | + self.country_code = cc + rates.push(*parse_rates) + end + rates + end + + +end # class + + + diff --git a/lib/currency/exchange/rate/source/historical.rb b/lib/currency/exchange/rate/source/historical.rb new file mode 100644 index 0000000..f620c1b --- /dev/null +++ b/lib/currency/exchange/rate/source/historical.rb @@ -0,0 +1,79 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source/base' + +# Gets historical rates from database using Active::Record. +# Rates are retrieved using Currency::Exchange::Rate::Source::Historical::Rate as +# a database record proxy. +# +# See Currency::Exchange::Rate::Source::Historical::Writer for a rate archiver. +# +class Currency::Exchange::Rate::Source::Historical < Currency::Exchange::Rate::Source::Base + + # Select specific rate source. + # Defaults to nil + attr_accessor :source + + def initialize + @source = nil # any + super + end + + + def source_key + @source ? @source.join(',') : '' + end + + + # This Exchange's name is the same as its #uri. + def name + "historical #{source_key}" + end + + + def initialize(*opt) + super + @rates_cache = { } + @raw_rates_cache = { } + end + + + def clear_rates + @rates_cache.clear + @raw_rates_cache.clear + super + end + + + # Returns a Rate. + def get_rate(c1, c2, time) + # rate = + get_rates(time).select{ | r | r.c1 == c1 && r.c2 == c2 }[0] + # $stderr.puts "#{self}.get_rate(#{c1}, #{c2}, #{time.inspect}) => #{rate.inspect}" + # rate + end + + + # Return a list of base Rates. + def get_rates(time = nil) + @rates_cache["#{source_key}:#{time}"] ||= + get_raw_rates(time).collect do | rr | + rr.to_rate + end + end + + + # Return a list of raw rates. + def get_raw_rates(time = nil) + @raw_rates_cache["#{source_key}:#{time}"] ||= + ::Currency::Exchange::Rate::Source::Historical::Rate.new(:c1 => nil, :c2 => nil, :date => time, :source => source). + find_matching_this(:all) + end + +end # class + + +require 'currency/exchange/rate/source/historical/rate' + + diff --git a/lib/currency/exchange/rate/source/historical/rate.rb b/lib/currency/exchange/rate/source/historical/rate.rb new file mode 100644 index 0000000..59d9746 --- /dev/null +++ b/lib/currency/exchange/rate/source/historical/rate.rb @@ -0,0 +1,184 @@ +require 'active_support' +require 'active_record/base' + +require 'currency/exchange/rate/source/historical' + +# This class represents a historical Rate in a database. +# It requires ActiveRecord. +# +class Currency::Exchange::Rate::Source::Historical::Rate < ::ActiveRecord::Base + @@_table_name ||= Currency::Config.current.historical_table_name + set_table_name @@_table_name + + # Can create a table and indices for this class + # when passed a Migration. + def self.__create_table(m, table_name = @@_table_name) + table_name = table_name.intern + m.instance_eval do + create_table table_name do |t| + t.column :created_on, :datetime, :null => false + t.column :updated_on, :datetime + + t.column :c1, :string, :limit => 3, :null => false + t.column :c2, :string, :limit => 3, :null => false + + t.column :source, :string, :limit => 32, :null => false + + t.column :rate, :float, :null => false + + t.column :rate_avg, :float + t.column :rate_samples, :integer + t.column :rate_lo, :float + t.column :rate_hi, :float + t.column :rate_date_0, :float + t.column :rate_date_1, :float + + t.column :date, :datetime, :null => false + t.column :date_0, :datetime + t.column :date_1, :datetime + + t.column :derived, :string, :limit => 64 + end + + add_index table_name, :c1 + add_index table_name, :c2 + add_index table_name, :source + add_index table_name, :date + add_index table_name, :date_0 + add_index table_name, :date_1 + add_index table_name, [:c1, :c2, :source, :date_0, :date_1], :name => 'c1_c2_src_date_range', :unique => true + end + end + + + # Initializes this object from a Currency::Exchange::Rate object. + def from_rate(rate) + self.c1 = rate.c1.code.to_s + self.c2 = rate.c2.code.to_s + self.rate = rate.rate + self.rate_avg = rate.rate_avg + self.rate_samples = rate.rate_samples + self.rate_lo = rate.rate_lo + self.rate_hi = rate.rate_hi + self.rate_date_0 = rate.rate_date_0 + self.rate_date_1 = rate.rate_date_1 + self.source = rate.source + self.derived = rate.derived + self.date = rate.date + self.date_0 = rate.date_0 + self.date_1 = rate.date_1 + self + end + + + # Convert all dates to localtime. + def dates_to_localtime! + self.date = self.date && self.date.clone.localtime + self.date_0 = self.date_0 && self.date_0.clone.localtime + self.date_1 = self.date_1 && self.date_1.clone.localtime + end + + + # Creates a new Currency::Exchange::Rate object. + def to_rate(cls = ::Currency::Exchange::Rate) + cls. + new( + ::Currency::Currency.get(self.c1), + ::Currency::Currency.get(self.c2), + self.rate, + "historical #{self.source}", + self.date, + self.derived, + { + :rate_avg => self.rate_avg, + :rate_samples => self.rate_samples, + :rate_lo => self.rate_lo, + :rate_hi => self.rate_hi, + :rate_date_0 => self.rate_date_0, + :rate_date_1 => self.rate_date_1, + :date_0 => self.date_0, + :date_1 => self.date_1 + }) + end + + + # Various defaults. + def before_validation + self.rate_avg = self.rate unless self.rate_avg + self.rate_samples = 1 unless self.rate_samples + self.rate_lo = self.rate unless self.rate_lo + self.rate_hi = self.rate unless self.rate_hi + self.rate_date_0 = self.rate unless self.rate_date_0 + self.rate_date_1 = self.rate unless self.rate_date_1 + + #self.date_0 = self.date unless self.date_0 + #self.date_1 = self.date unless self.date_1 + self.date = self.date_0 + (self.date_1 - self.date_0) * 0.5 if ! self.date && self.date_0 && self.date_1 + self.date = self.date_0 unless self.date + self.date = self.date_1 unless self.date + end + + + # Returns a ActiveRecord::Base#find :conditions value + # to locate any rates that will match this one. + # + # source may be a list of sources. + # date will match inside date_0 ... date_1 or exactly. + # + def find_matching_this_conditions + sql = [ ] + values = [ ] + + if self.c1 + sql << 'c1 = ?' + values.push(self.c1.to_s) + end + + if self.c2 + sql << 'c2 = ?' + values.push(self.c2.to_s) + end + + if self.source + if self.source.kind_of?(Array) + sql << 'source IN ?' + else + sql << 'source = ?' + end + values.push(self.source) + end + + if self.date + sql << '(((date_0 IS NULL) OR (date_0 <= ?)) AND ((date_1 IS NULL) OR (date_1 > ?))) OR date = ?' + values.push(self.date, self.date, self.date) + end + + if self.date_0 + sql << 'date_0 = ?' + values.push(self.date_0) + end + + if self.date_1 + sql << 'date_1 = ?' + values.push(self.date_1) + end + + sql << '1 = 1' if sql.empty? + + values.unshift(sql.collect{|x| "(#{x})"}.join(' AND ')) + + # $stderr.puts "values = #{values.inspect}" + + values + end + + + # Shorthand. + def find_matching_this(opt1 = :all, *opts) + self.class.find(opt1, :conditions => find_matching_this_conditions, *opts) + end + + end # class + + + diff --git a/lib/currency/exchange/rate/source/historical/rate_loader.rb b/lib/currency/exchange/rate/source/historical/rate_loader.rb new file mode 100644 index 0000000..f0d18a6 --- /dev/null +++ b/lib/currency/exchange/rate/source/historical/rate_loader.rb @@ -0,0 +1,186 @@ +require 'currency/exchange/rate/source/historical' +require 'currency/exchange/rate/source/historical/rate' +require 'currency/exchange/rate/source/historical/writer' + + +# Currency::Config.current.historical_table_name = 'currency_rates' +# opts['uri_path'] ||= 'syndicated/cnusa/fxrates.xml' + +# Loads rates from multiple sources and will store them +# as historical rates in a database. + +class ::Currency::Exchange::Rate::Source::Historical::RateLoader + attr_accessor :options + attr_accessor :source_options + attr_accessor :required_currencies + attr_accessor :rate_sources + attr_accessor :rate_source_options + attr_accessor :verbose + attr_accessor :preferred_summary_source + attr_accessor :base_currencies + attr_accessor :summary_rate_src + attr_reader :writer + + def initialize(opts = { }) + self.summary_rate_src = 'summary' + self.source_options = { } + self.options = opts.dup.freeze + self.base_currencies = [ :USD ] + self.required_currencies = + [ + :USD, + :GBP, + :CAD, + :EUR, + # :MXP, + ] + self.verbose = ! ! ENV['CURRENCY_VERBOSE'] + opts.each do | k, v | + setter = "#{k}=" + send(setter, v) if respond_to?(setter) + end + end + + + def initialize_writer(writer = Currency::Exchange::Rate::Source::Historical::Writer.new) + @writer = writer + + writer.time_quantitizer = :current + writer.required_currencies = required_currencies + writer.base_currencies = base_currencies + writer.preferred_currencies = writer.required_currencies + writer.reciprocal_rates = true + writer.all_rates = true + writer.identity_rates = false + + options.each do | k, v | + setter = "#{k}=" + writer.send(setter, v) if writer.respond_to?(setter) + end + + writer + end + + + def run + rate_sources.each do | src | + # Create a historical rate writer. + initialize_writer + + # Handle creating a summary rates called 'summary'. + if src == summary_rate_src + summary_rates(src) + else + require "currency/exchange/rate/source/#{src}" + src_cls_name = src.gsub(/(^|_)([a-z])/) { | m | $2.upcase } + src_cls = Currency::Exchange::Rate::Source.const_get(src_cls_name) + src = src_cls.new(source_options) + + writer.source = src + + writer.write_rates + end + end + ensure + @writer = nil + end + + + def summary_rates(src) + # A list of summary rates. + summary_rates = [ ] + + # Get a list of all rate time ranges before today, + # that do not have a 'cnu' summary rate. + h_rate_cls = Currency::Exchange::Rate::Source::Historical::Rate + conn = h_rate_cls.connection + + # Select only rates from yesterday or before back till 30 days. + date_1 = Time.now - (0 * 24 * 60 * 60) + date_0 = date_1 - (30 * 24 * 60 * 60) + + date_0 = conn.quote(date_0) + date_1 = conn.quote(date_1) + + query = +"SELECT + DISTINCT a.date_0, a.date_1 +FROM + #{h_rate_cls.table_name} AS a +WHERE + a.source <> '#{src}' + AND a.date_1 >= #{date_0} AND a.date_1 < #{date_1} + AND (SELECT COUNT(b.id) FROM #{h_rate_cls.table_name} AS b + WHERE + b.c1 = a.c1 AND b.c2 = a.c2 + AND b.date_0 = a.date_0 AND b.date_1 = a.date_1 + AND b.source = '#{src}') = 0 +ORDER BY + date_0" + STDERR.puts "query = \n#{query.split("\n").join(' ')}" if verbose + + dates = conn.query(query) + + dates.each do | date_range | + STDERR.puts "\n=============================================\n" if verbose + STDERR.puts "date_range = #{date_range.inspect}" if verbose + + # Query for all rates that have the same date range. + q_rate = h_rate_cls.new(:date_0 => date_range[0], :date_1 => date_range[1]) + available_rates = q_rate.find_matching_this(:all) + + # Collect all the currency pairs and rates. + currency_pair = { } + available_rates.each do | h_rate | + rate = h_rate.to_rate + (currency_pair[ [ rate.c1, rate.c2 ] ] ||= [ ]) << [ h_rate, rate ] + # STDERR.puts "rate = #{rate} #{h_rate.date_0} #{h_rate.date_1}" if verbose + end + + currency_pair.each_pair do | currency_pair, rates | + STDERR.puts "\n =============================================\n" if verbose + STDERR.puts " currency_pair = #{currency_pair}" if verbose + + # Create a summary rate for the currency pair. + selected_rates = [ ] + + rates.each do | h_rates | + h_rate, rate = *h_rates + + # Sanity check! + next if h_rate.source == src + + # Found perferred source? + if h_rate.source == preferred_summary_source + selected_rates = [ h_rates ] + break + end + + selected_rates << h_rates + end + + unless selected_rates.empty? + summary_rate = Currency::Exchange::Rate::Writable.new(currency_pair[0], currency_pair[1], 0.0) + selected_rates.each do | h_rates | + h_rate, rate = *h_rates + STDERR.puts " rate = #{rate.inspect}" if verbose + summary_rate.collect_rate(rate) + end + + # Save the rate. + summary_rate.rate = summary_rate.rate_avg + summary_rate.source = src + summary_rate.derived = 'summary(' + selected_rates.collect{|r| r[0].id}.sort.join(',') + ')' + STDERR.puts " summary_rate = #{summary_rate} #{summary_rate.rate_samples}" if verbose + + summary_rates << summary_rate + end + end + end + + writer.write_rates(summary_rates) + end + +end + + diff --git a/lib/currency/exchange/rate/source/historical/writer.rb b/lib/currency/exchange/rate/source/historical/writer.rb new file mode 100644 index 0000000..5665073 --- /dev/null +++ b/lib/currency/exchange/rate/source/historical/writer.rb @@ -0,0 +1,220 @@ + +require 'currency/exchange/rate/source/historical' + +# Responsible for writing historical rates from a rate source. +class Currency::Exchange::Rate::Source::Historical::Writer + + # Error during handling of historical rates. + class Error < ::Currency::Exception::Base; end + + # The source of rates. + attr_accessor :source + + # If true, compute all Rates between rates. + # This can be used to aid complex join reports that may assume + # c1 as the from currency and c2 as the to currency. + attr_accessor :all_rates + + # If true, store identity rates. + # This can be used to aid complex join reports. + attr_accessor :identity_rates + + # If true, compute and store all reciprocal rates. + attr_accessor :reciprocal_rates + + # If set, a set of preferred currencies. + attr_accessor :preferred_currencies + + # If set, a list of required currencies. + attr_accessor :required_currencies + + # If set, a list of required base currencies. + # base currencies must have rates as c1. + attr_accessor :base_currencies + + # If set, use this time quantitizer to + # manipulate the Rate date_0 date_1 time ranges. + # If :default, use the TimeQuantitizer.default. + attr_accessor :time_quantitizer + + + def initialize(opt = { }) + @all_rates = true + @identity_rates = false + @reciprocal_rates = true + @preferred_currencies = nil + @required_currencies = nil + @base_currencies = nil + @time_quantitizer = nil + opt.each_pair{| k, v | self.send("#{k}=", v) } + end + + + # Returns a list of selected rates from source. + def selected_rates + # Produce a list of all currencies. + currencies = source.currencies + + # $stderr.puts "currencies = #{currencies.join(', ')}" + + selected_rates = [ ] + + # Get list of preferred_currencies. + if self.preferred_currencies + self.preferred_currencies = self.preferred_currencies.collect do | c | + ::Currency::Currency.get(c) + end + currencies = currencies.select do | c | + self.preferred_currencies.include?(c) + end.uniq + end + + + # Check for required currencies. + if self.required_currencies + self.required_currencies = self.required_currencies.collect do | c | + ::Currency::Currency.get(c) + end + + self.required_currencies.each do | c | + unless currencies.include?(c) + raise ::Currency::Exception::MissingCurrency, + [ + "Required currency #{c.inspect} not in #{currencies.inspect}", + :currency, c, + :required_currency, currencies, + ] + end + end + end + + + # $stderr.puts "currencies = #{currencies.inspect}" + + deriver = ::Currency::Exchange::Rate::Deriver.new(:source => source) + + # Produce Rates for all pairs of currencies. + if all_rates + currencies.each do | c1 | + currencies.each do | c2 | + next if c1 == c2 && ! identity_rates + rate = deriver.rate(c1, c2, nil) + selected_rates << rate unless selected_rates.include?(rate) + end + end + elsif base_currencies + base_currencies.each do | c1 | + c1 = ::Currency::Currency.get(c1) + currencies.each do | c2 | + next if c1 == c2 && ! identity_rates + rate = deriver.rate(c1, c2, nil) + selected_rates << rate unless selected_rates.include?(rate) + end + end + else + selected_rates = source.rates.select do | r | + next if r.c1 == r.c2 && ! identity_rates + currencies.include?(r.c1) && currencies.include?(r.c2) + end + end + + if identity_rates + currencies.each do | c1 | + c1 = ::Currency::Currency.get(c1) + c2 = c1 + rate = deriver.rate(c1, c2, nil) + selected_rates << rate unless selected_rates.include?(rate) + end + else + selected_rates = selected_rates.select do | r | + r.c1 != r.c2 + end + end + + if reciprocal_rates + selected_rates.clone.each do | r | + c1 = r.c2 + c2 = r.c1 + rate = deriver.rate(c1, c2, nil) + selected_rates << rate unless selected_rates.include?(rate) + end + end + + # $stderr.puts "selected_rates = #{selected_rates.inspect}\n [#{selected_rates.size}]" + + selected_rates + end + + + # Returns an Array of Historical::Rate objects that were written. + # Avoids writing Rates that already have been written. + def write_rates(rates = selected_rates) + + # Create Historical::Rate objects. + h_rate_class = ::Currency::Exchange::Rate::Source::Historical::Rate + + # Most Rates from the same Source will probably have the same time, + # so cache the computed date_range. + date_range_cache = { } + rate_0 = nil + if time_quantitizer = self.time_quantitizer + time_quantitizer = ::Currency::Exchange::TimeQuantitizer.current if time_quantitizer == :current + end + + h_rates = rates.collect do | r | + rr = h_rate_class.new.from_rate(r) + rr.dates_to_localtime! + + if rr.date && time_quantitizer + date_range = date_range_cache[rr.date] ||= time_quantitizer.quantitize_time_range(rr.date) + rr.date_0 = date_range.begin + rr.date_1 = date_range.end + end + + rate_0 ||= rr if rr.date_0 && rr.date_1 + + rr + end + + # Fix any dateless Rates. + if rate_0 + h_rates.each do | rr | + rr.date_0 = rate_0.date_0 unless rr.date_0 + rr.date_1 = rate_0.date_1 unless rr.date_1 + end + end + + # Save them all or none. + stored_h_rates = [ ] + h_rate_class.transaction do + h_rates.each do | rr | + # Skip identity rates. + next if rr.c1 == rr.c2 && ! identity_rates + + # Skip if already exists. + existing_rate = rr.find_matching_this(:first) + if existing_rate + stored_h_rates << existing_rate # Already existed. + else + begin + rr.save! + rescue Object => err + raise ::Currency::Exception::Generic, + [ + "During save of #{rr.inspect}", + :error, err, + ] + end + stored_h_rates << rr # Written. + end + end + end + + # Return written Historical::Rates. + stored_h_rates + end + +end # class + + + diff --git a/lib/currency/exchange/rate/source/new_york_fed.rb b/lib/currency/exchange/rate/source/new_york_fed.rb new file mode 100644 index 0000000..e5733b0 --- /dev/null +++ b/lib/currency/exchange/rate/source/new_york_fed.rb @@ -0,0 +1,127 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source/base' + +require 'net/http' +require 'open-uri' +require 'rexml/document' + + +# Connects to http://www.newyorkfed.org/markets/fxrates/FXtoXML.cfm +# ?FEXdate=2007%2D02%2D14%2000%3A00%3A00%2E0&FEXtime=1200 and parses XML. +# +# No rates are available on Saturday and Sunday. +# +class Currency::Exchange::Rate::Source::NewYorkFed < ::Currency::Exchange::Rate::Source::Provider + # Defines the pivot currency for http://xe.com/. + PIVOT_CURRENCY = :USD + + def initialize(*opt) + self.uri = 'http://www.newyorkfed.org/markets/fxrates/FXtoXML.cfm?FEXdate=#{date_YYYY}%2D#{date_MM}%2D#{date_DD}%2000%3A00%3A00%2E0&FEXTIME=1200' + @raw_rates = nil + super(*opt) + end + + + # Returns 'newyorkfed.org'. + def name + 'newyorkfed.org' + end + + + # New York Fed rates are not available on Saturday and Sunday. + def available?(time = nil) + time ||= Time.now + ! [0, 6].include?(time.wday) ? true : false + end + + + def clear_rates + @raw_rates = nil + super + end + + + def raw_rates + rates + @raw_rates + end + + + # The fed swaps rates on some currency pairs! + # See http://www.newyorkfed.org/markets/fxrates/noon.cfm (LISTS AUD!) + # http://www.newyorkfed.org/xml/fx.html (DOES NOT LIST AUD!) + @@swap_units = { + :AUD => true, + :EUR => true, + :NZD => true, + :GBP => true, + } + + + # Parses XML for rates. + def parse_rates(data = nil) + data = get_page_content unless data + + rates = [ ] + + @raw_rates = { } + + $stderr.puts "#{self}: parse_rates: data =\n#{data}" if @verbose + + doc = REXML::Document.new(data).root + x_series = doc.elements.to_a('//frbny:Series') + raise ParserError, "no UNIT attribute" unless x_series + x_series.each do | series | + c1 = series.attributes['UNIT'] # WHAT TO DO WITH @UNIT_MULT? + raise ParserError, "no UNIT attribute" unless c1 + c1 = c1.upcase.intern + + c2 = series.elements.to_a('frbny:Key/frbny:CURR')[0].text + raise ParserError, "no frbny:CURR element" unless c2 + c2 = c2.upcase.intern + + rate = series.elements.to_a('frbny:Obs/frbny:OBS_VALUE')[0] + raise ParserError, 'no frbny:OBS_VALUE' unless rate + rate = rate.text.to_f + + date = series.elements.to_a('frbny:Obs/frbny:TIME_PERIOD')[0] + raise ParserError, 'no frbny:TIME_PERIOD' unless date + date = date.text + date = Time.parse("#{date} 12:00:00 -05:00") # USA NY => EST + + # Handle arbitrary rate reciprocals! + if @@swap_units[c1] || @@swap_units[c2] + c1, c2 = c2, c1 + end + + rates << new_rate(c1, c2, rate, date) + + (@raw_rates[c1] ||= { })[c2] ||= rate + (@raw_rates[c2] ||= { })[c1] ||= 1.0 / rate + end + + # $stderr.puts "rates = #{rates.inspect}" + raise ::Currency::Exception::UnavailableRates, + [ + "No rates found in #{get_uri.inspect}", + :uri, get_uri, + ] if rates.empty? + + rates + end + + + # Return a list of known base rates. + def load_rates(time = nil) + # $stderr.puts "#{self}: load_rates(#{time})" if @verbose + self.date = time + parse_rates + end + + +end # class + + + diff --git a/lib/currency/exchange/rate/source/provider.rb b/lib/currency/exchange/rate/source/provider.rb new file mode 100644 index 0000000..d626f12 --- /dev/null +++ b/lib/currency/exchange/rate/source/provider.rb @@ -0,0 +1,120 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source' + + +# Base class for rate data providers. +# Assumes that rate sources provide more than one rate per query. +class Currency::Exchange::Rate::Source::Provider < Currency::Exchange::Rate::Source::Base + + # Error during parsing of rates. + class ParserError < ::Currency::Exception::RateSourceError; end + + # The URI used to access the rate source. + attr_accessor :uri + + # The URI path relative to uri used to access the rate source. + attr_accessor :uri_path + + # The Time used to query the rate source. + # Typically set by #load_rates. + attr_accessor :date + + # The name is the same as its #uri. + alias :name :uri + + def initialize(*args) + super + @rates = { } + end + + # Returns the date to query for rates. + # Defaults to yesterday. + def date + @date || (Time.now - 24 * 60 * 60) # yesterday. + end + + + # Returns year of query date. + def date_YYYY + '%04d' % date.year + end + + + # Return month of query date. + def date_MM + '%02d' % date.month + end + + + # Returns day of query date. + def date_DD + '%02d' % date.day + end + + + # Returns the URI string as evaluated with this object. + def get_uri + uri = self.uri + uri = "\"#{uri}\"" + uri = instance_eval(uri) + $stderr.puts "#{self}: uri = #{uri.inspect}" if @verbose + uri + end + + + # Returns the URI content. + def get_page_content + data = open(get_uri) { |data| data.read } + + data + end + + + # Clear cached rates from this source. + def clear_rates + @rates.clear + super + end + + + # Returns current base Rates or calls load_rates to load them from the source. + def rates(time = nil) + time = time && normalize_time(time) + @rates["#{time}"] ||= load_rates(time) + end + + + # Returns an array of base Rates from the rate source. + # + # Subclasses must define this method. + def load_rates(time = nil) + raise Currency::Exception::SubclassResponsibility, :load_rates + end + + + # Return a matching base rate. + def get_rate(c1, c2, time) + rates.each do | rate | + return rate if + rate.c1 == c1 && + rate.c2 == c2 && + (! time || normalize_time(rate.date) == time) + end + + nil + end + + alias :get_rate_base :get_rate + + + # Returns true if a rate provider is available. + def available?(time = nil) + true + end + +end # class + + + diff --git a/lib/currency/exchange/rate/source/test.rb b/lib/currency/exchange/rate/source/test.rb new file mode 100644 index 0000000..2f01838 --- /dev/null +++ b/lib/currency/exchange/rate/source/test.rb @@ -0,0 +1,50 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source/provider' + +# This class is a test Rate Source. +# It can provide only fixed rates between USD, CAD and EUR. +# Used only for test purposes. +# DO NOT USE THESE RATES FOR A REAL APPLICATION. +class Currency::Exchange::Rate::Source::Test < Currency::Exchange::Rate::Source::Provider + @@instance = nil + + # Returns a singleton instance. + def self.instance(*opts) + @@instance ||= self.new(*opts) + end + + + def initialize(*opts) + self.uri = 'none://localhost/Test' + super(*opts) + end + + + def name + 'Test' + end + + # Test rate from :USD to :CAD. + def self.USD_CAD; 1.1708; end + + + # Test rate from :USD to :EUR. + def self.USD_EUR; 0.7737; end + + + # Test rate from :USD to :GBP. + def self.USD_GBP; 0.5098; end + + + # Returns test Rate for USD to [ CAD, EUR, GBP ]. + def rates + [ new_rate(:USD, :CAD, self.class.USD_CAD), + new_rate(:USD, :EUR, self.class.USD_EUR), + new_rate(:USD, :GBP, self.class.USD_GBP) ] + end + +end # class + + diff --git a/lib/currency/exchange/rate/source/the_financials.rb b/lib/currency/exchange/rate/source/the_financials.rb new file mode 100644 index 0000000..7c02b95 --- /dev/null +++ b/lib/currency/exchange/rate/source/the_financials.rb @@ -0,0 +1,191 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source/base' + +require 'net/http' +require 'open-uri' +require 'rexml/document' + + +# Connects to http://www.thefinancials.com and parses XML. +# +# This is for demonstration purposes. +# +class Currency::Exchange::Rate::Source::TheFinancials < ::Currency::Exchange::Rate::Source::Provider + # Defines the pivot currency for http://thefinancials.com/. + PIVOT_CURRENCY = :USD + + def initialize(*opt) + @raw_rates = nil + self.uri_path = 'syndicated/UNKNOWN/fxrates.xml' + super(*opt) + self.uri = "http://www.thefinancials.com/#{self.uri_path}" + end + + + # Returns 'thefinancials.com'. + def name + 'thefinancials.org' + end + + +# def get_page_content +# test_content +# end + + + def clear_rates + @raw_rates = nil + super + end + + + def raw_rates + rates + @raw_rates + end + + + # Parses XML for rates. + def parse_rates(data = nil) + data = get_page_content unless data + + rates = [ ] + + @raw_rates = { } + + # $stderr.puts "parse_rates: data = #{data}" + + doc = REXML::Document.new(data).root + doc.elements.to_a('//record').each do | record | + c1_c2 = record.elements.to_a('symbol')[0].text + md = /([A-Z][A-Z][A-Z]).*?([A-Z][A-Z][A-Z])/.match(c1_c2) + c1, c2 = md[1], md[2] + + c1 = c1.upcase.intern + c2 = c2.upcase.intern + + rate = record.elements.to_a('last')[0].text.to_f + + date = record.elements.to_a('date')[0].text + date = Time.parse("#{date} 12:00:00 -05:00") # USA NY => EST + + rates << new_rate(c1, c2, rate, date) + + (@raw_rates[c1] ||= { })[c2] ||= rate + end + + rates + end + + + # Return a list of known base rates. + def load_rates(time = nil) + self.date = time + parse_rates + end + + + def test_content + <<EOF +<?xml version="1.0" ?> +<TFCRecords> +<record> +<symbol>USD/EUR</symbol> +<date>10/25/2001</date> +<last>1.115822</last> +</record> +<record> +<symbol>USD/AUD</symbol> +<date>10/25/2001</date> +<last>1.975114</last> +</record> +<record> +<symbol>USD/CAD</symbol> +<date>10/25/2001</date> +<last>1.57775</last> +</record> +<record> +<symbol>USD/CNY</symbol> +<date>10/25/2001</date> +<last>8.2769</last> +</record> +<record> +<symbol>USD/ESP</symbol> +<date>10/25/2001</date> +<last>185.65725</last> +</record> +<record> +<symbol>USD/GBP</symbol> +<date>10/25/2001</date> +<last>0.698849867830019</last> +</record> +<record> +<symbol>USD/HKD</symbol> +<date>10/25/2001</date> +<last>7.7999</last> +</record> +<record> +<symbol>USD/IDR</symbol> +<date>10/25/2001</date> +<last>10265</last> +</record> +<record> +<symbol>USD/INR</symbol> +<date>10/25/2001</date> +<last>48.01</last> +</record> +<record> +<symbol>USD/JPY</symbol> +<date>10/25/2001</date> +<last>122.68</last> +</record> +<record> +<symbol>USD/KRW</symbol> +<date>10/25/2001</date> +<last>1293.5</last> +</record> +<record> +<symbol>USD/MYR</symbol> +<date>10/25/2001</date> +<last>3.8</last> +</record> +<record> +<symbol>USD/NZD</symbol> +<date>10/25/2001</date> +<last>2.41485</last> +</record> +<record> +<symbol>USD/PHP</symbol> +<date>10/25/2001</date> +<last>52.05</last> +</record> +<record> +<symbol>USD/PKR</symbol> +<date>10/25/2001</date> +<last>61.6</last> +</record> +<record> +<symbol>USD/SGD</symbol> +<date>10/25/2001</date> +<last>1.82615</last> +</record> +<record> +<symbol>USD/THB</symbol> +<date>10/25/2001</date> +<last>44.88</last> +</record> +<record> +<symbol>USD/TWD</symbol> +<date>10/25/2001</date> +<last>34.54</last> +</record> +</TFCRecords> +EOF + end + +end # class + + + diff --git a/lib/currency/exchange/rate/source/timed_cache.rb b/lib/currency/exchange/rate/source/timed_cache.rb new file mode 100644 index 0000000..9a6c75e --- /dev/null +++ b/lib/currency/exchange/rate/source/timed_cache.rb @@ -0,0 +1,198 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source/base' + +# A timed cache for rate sources. +# +# This class should be used at the top-level of a rate source change, +# to correctly check rate dates. +# +class Currency::Exchange::Rate::Source::TimedCache < ::Currency::Exchange::Rate::Source::Base + # The rate source. + attr_accessor :source + + # Defines the number of seconds rates until rates + # become invalid, causing a request of new rates. + # + # Defaults to 600 seconds. + attr_accessor :time_to_live + + + # Defines the number of random seconds to add before + # rates become invalid. + # + # Defaults to 30 seconds. + attr_accessor :time_to_live_fudge + + + # Returns the time of the last load. + attr_reader :rate_load_time + + + # Returns the time of the next load. + attr_reader :rate_reload_time + + + # Returns source's name. + def name + source.name + end + + + def initialize(*opt) + self.time_to_live = 600 + self.time_to_live_fudge = 30 + @rate_load_time = nil + @rate_reload_time = nil + @processing_rates = false + @cached_rates = { } + @cached_rates_old = nil + super(*opt) + end + + + # Clears current rates. + def clear_rates + @cached_rates = { } + @source.clear_rates + super + end + + + # Returns true if the cache of Rates + # is expired. + def expired? + if @time_to_live && + @rate_reload_time && + (Time.now > @rate_reload_time) + + if @cached_rates + $stderr.puts "#{self}: rates expired on #{@rate_reload_time}" if @verbose + + @cached_rates_old = @cached_rates + end + + clear_rates + + true + else + false + end + end + + + # Check expired? before returning a Rate. + def rate(c1, c2, time) + if expired? + clear_rates + end + super(c1, c2, time) + end + + + def get_rate(c1, c2, time) + # STDERR.puts "get_rate #{c1} #{c2} #{time}" + rates = load_rates(time) + # STDERR.puts "rates = #{rates.inspect}" + rate = rates && (rates.select{|x| x.c1 == c1 && x.c2 == c2}[0]) + # STDERR.puts "rate = #{rate.inspect}" + rate + end + + + # Returns an array of all the cached Rates. + def rates(time = nil) + load_rates(time) + end + + + # Returns an array of all the cached Rates. + def load_rates(time = nil) + # Check expiration. + expired? + + # Return rates, if cached. + return rates if rates = @cached_rates["#{time}"] + + # Force load of rates. + rates = @cached_rates["#{time}"] = _load_rates_from_source(time) + + # Update expiration. + _calc_rate_reload_time + + return nil unless rates + + # Flush old rates. + @cached_rates_old = nil + + rates + end + + + def time_to_live=(x) + @time_to_live = x + _calc_rate_reload_time + x + end + + + def time_to_live_fudge=(x) + @time_to_live_fudge = x + _calc_rate_reload_time + x + end + + + def _calc_rate_reload_time + if @time_to_live && @rate_load_time + @rate_reload_time = @rate_load_time + (@time_to_live + (@time_to_live_fudge || 0)) + $stderr.puts "#{self}: rates expire on #{@rate_reload_time}" if @verbose + end + + end + + + + def _load_rates_from_source(time = nil) # :nodoc: + rates = nil + + begin + # Do not allow re-entrancy + raise Currency::Exception::InvalidReentrancy, "Reentry!" if @processing_rates + + # Begin processing new rate request. + @processing_rates = true + + # Clear cached Rates. + clear_rates + + # Load rates from the source. + rates = source.load_rates(time) + + # Compute new rate timestamp. + @rate_load_time = Time.now + + # STDERR.puts "rate_load_time = #{@rate_load_time}" + ensure + # End processsing new rate request. + @processing_rates = false + + end + + # STDERR.puts "_load_rates => #{rates.inspect}" + + rates + end + + + # Returns true if the underlying rate provider is available. + def available?(time = nil) + source.available?(time) + end + + +end # class + + + diff --git a/lib/currency/exchange/rate/source/xe.rb b/lib/currency/exchange/rate/source/xe.rb new file mode 100644 index 0000000..609a9d1 --- /dev/null +++ b/lib/currency/exchange/rate/source/xe.rb @@ -0,0 +1,165 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'currency/exchange/rate/source/base' + +require 'net/http' +require 'open-uri' +# Cant use REXML because of missing </form> tags -- 2007/03/11 +# require 'rexml/document' + +# Connects to http://xe.com and parses "XE.com Quick Cross Rates" +# from home page HTML. +# +class Currency::Exchange::Rate::Source::Xe < ::Currency::Exchange::Rate::Source::Provider + + # Defines the pivot currency for http://xe.com/. + PIVOT_CURRENCY = :USD + + def initialize(*opt) + self.uri = 'http://xe.com/' + self.pivot_currency = PIVOT_CURRENCY + @raw_rates = nil + super(*opt) + end + + + # Returns 'xe.com'. + def name + 'xe.com' + end + + + def clear_rates + @raw_rates = nil + super + end + + + # Returns a cached Hash of rates: + # + # xe.raw_rates[:USD][:CAD] => 1.0134 + # + def raw_rates + # Force load of rates + @raw_rates ||= parse_page_rates + end + + + + # Parses http://xe.com homepage HTML for + # quick rates of 10 currencies. + def parse_page_rates(data = nil) + data = get_page_content unless data + + @lines = data = data.split(/\n/); + + # xe.com no longer gives date/time. + # Remove usecs. + time = Time.at(Time.new.to_i).getutc + @rate_timestamp = time + + eat_lines_until /More currencies\.\.\.<\/a>/i + eat_lines_until /^\s*<tr>/i + eat_lines_until /^\s*<tr>/i + + # Read first table row to get position for each currency + currency = [ ] + eat_lines_until /^\s*<\/tr>/i do + if md = /<td[^>]+?>.*?\/> ([A-Z][A-Z][A-Z])<\/td>/.match(@line) + cur = md[1].intern + cur_i = currency.size + currency.push(cur) + $stderr.puts "Found currency header: #{cur.inspect} at #{cur_i}" if @verbose + end + end + raise ParserError, "Currencies header not found" if currency.empty? + + + # Skip until "1 USD =" + eat_lines_until /^\s*<td[^>]+?> 1&nbsp;+USD&nbsp;=/ + + # Read first row of 1 USD = ... + rate = { } + cur_i = -1 + eat_lines_until /^\s*<\/tr>/i do + # Grok: + # + # <td align="center" class="cur2 currencyA">114.676</td>\n + # + # AND + # + # <td align="center" class="cur2 currencyA"><div id="positionImage">0.9502\n + # + if md = /<td[^>]+?>\s*(<div[^>]+?>\s*)?(\d+\.\d+)\s*(<\/td>)?/i.match(@line) + usd_to_cur = md[2].to_f + cur_i = cur_i + 1 + cur = currency[cur_i] + raise ParserError, "Currency not found at column #{cur_i}" unless cur + next if cur.to_s == PIVOT_CURRENCY.to_s + (rate[PIVOT_CURRENCY] ||= {})[cur] = usd_to_cur + (rate[cur] ||= { })[PIVOT_CURRENCY] ||= 1.0 / usd_to_cur + $stderr.puts "#{cur.inspect} => #{usd_to_cur}" if @verbose + end + end + + raise ::Currency::Exception::UnavailableRates, "No rates found in #{get_uri.inspect}" if rate.keys.empty? + + raise ParserError, + [ + "Not all currencies found", + :expected_currences, currency, + :found_currencies, rate.keys, + :missing_currencies, currency - rate.keys, + ] if rate.keys.size != currency.size + + @lines = @line = nil + + raise ParserError, "Rate date not found" unless @rate_timestamp + + rate + end + + + def eat_lines_until(rx) + until @lines.empty? + @line = @lines.shift + if md = rx.match(@line) + $stderr.puts "\nMATCHED #{@line.inspect} WITH #{rx.inspect} AT LINES:\n#{@lines[0..4].inspect}" if @verbose + return md + end + yield @line if block_given? + end + + raise ParserError, [ 'eat_lines_until failed', :rx, rx ] + + false + end + + + # Return a list of known base rates. + def load_rates(time = nil) + if time + $stderr.puts "#{self}: WARNING CANNOT SUPPLY HISTORICAL RATES" unless @time_warning + @time_warning = true + end + + rates = raw_rates # Load rates + rates_pivot = rates[PIVOT_CURRENCY] + raise ::Currency::Exception::UnknownRate, + [ + "Cannot get base rate #{PIVOT_CURRENCY.inspect}", + :pivot_currency, PIVOT_CURRENCY, + ] unless rates_pivot + + result = rates_pivot.keys.collect do | c2 | + new_rate(PIVOT_CURRENCY, c2, rates_pivot[c2], @rate_timestamp) + end + + result + end + + +end # class + + diff --git a/lib/currency/exchange/time_quantitizer.rb b/lib/currency/exchange/time_quantitizer.rb new file mode 100644 index 0000000..0f9337d --- /dev/null +++ b/lib/currency/exchange/time_quantitizer.rb @@ -0,0 +1,111 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +# = Currency::Exchange::TimeQuantitizer +# +# The Currency::Exchange::TimeQuantitizer quantitizes time values +# such that money values and rates at a given time +# can be turned into a hash key, depending +# on the rate source's temporal accuracy. +# +class Currency::Exchange::TimeQuantitizer + + def self.current; @current ||= self.new; end + def self.current=(x); @current = x; end + + # Time quantitization size. + # Defaults to 1 day. + attr_accessor :time_quant_size + + # Time quantization offset in seconds. + # This is applied to epoch time before quantization. + # If nil, uses Time#utc_offset. + # Defaults to nil. + attr_accessor :time_quant_offset + + def initialize(*opt) + @time_quant_size ||= 60 * 60 * 24 + @time_quant_offset ||= nil + opt = Hash[*opt] + opt.each_pair{|k,v| self.send("#{k}=", v)} + end + + + # Normalizes time to a quantitized value. + # For example: a time_quant_size of 60 * 60 * 24 will + # truncate a rate time to a particular day. + # + # Subclasses can override this method. + def quantitize_time(time) + # If nil, then nil. + return time unless time + + # Get bucket parameters. + was_utc = time.utc? + quant_offset = time_quant_offset + quant_offset ||= time.utc_offset + # $stderr.puts "quant_offset = #{quant_offset}" + quant_size = time_quant_size.to_i + + # Get offset from epoch. + time = time.tv_sec + + # Remove offset (timezone) + time += quant_offset + + # Truncate to quantitize size. + time = (time.to_i / quant_size) * quant_size + + # Add offset (timezone) + time -= quant_offset + + # Convert back to Time object. + time = Time.at(time) + + # Quant to day? + # NOTE: is this due to a Ruby bug, or + # some wierd UTC time-flow issue, like leap-seconds. + if quant_size == 60 * 60 * 24 + time = time + 60 * 60 + if was_utc + time = time.getutc + time = Time.utc(time.year, time.month, time.day, 0, 0, 0, 0) + else + time = Time.local(time.year, time.month, time.day, 0, 0, 0, 0) + end + end + + # Convert back to UTC? + time = time.getutc if was_utc + + time + end + + # Returns a Range of Time such that: + # + # range.include?(time) + # ! range.include?(time + time_quant_size) + # ! range.include?(time - time_quant_size) + # range.exclude_end? + # + # The range.max is end-exclusive to avoid precision issues: + # + # t = Time.now + # => Thu Feb 15 15:32:34 EST 2007 + # x.quantitize_time_range(t) + # => Thu Feb 15 00:00:00 EST 2007...Fri Feb 16 00:00:00 EST 2007 + # + def quantitize_time_range(time) + time_0 = quantitize_time(time) + time_1 = time_0 + time_quant_size.to_i + time_0 ... time_1 + end + + # Returns a simple string rep. + def to_s + "#<#{self.class.name} #{quant_offset} #{quant_size}>" + end + +end # class + + diff --git a/lib/currency/formatter.rb b/lib/currency/formatter.rb new file mode 100644 index 0000000..50bf54f --- /dev/null +++ b/lib/currency/formatter.rb @@ -0,0 +1,300 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'rss/rss' # Time#xmlschema + + +# This class formats a Money value as a String. +# Each Currency has a default Formatter. +class Currency::Formatter + # The underlying object for Currency::Formatter#format. + # This object is cloned and initialized with strings created + # from Formatter#format. + # It handles the Formatter#format string interpolation. + class Template + @@empty_hash = { } + @@empty_hash.freeze + + # The template string. + attr_accessor :template + + # The Currency::Money object being formatted. + attr_accessor :money + # The Currency::Currency object being formatted. + attr_accessor :currency + + # The sign: '-' or nil. + attr_accessor :sign + # The whole part of the value, with thousands_separator or nil. + attr_accessor :whole + # The fraction part of the value, with decimal_separator or nil. + attr_accessor :fraction + # The currency symbol or nil. + attr_accessor :symbol + # The currency code or nil. + attr_accessor :code + + # The time or nil. + attr_accessor :time + + def initialize(opts = @@empty_hash) + @template = + @template_proc = + nil + + opts.each_pair{ | k, v | self.send("#{k}=", v) } + end + + + # Sets the template string and uncaches the template_proc. + def template=(x) + if @template != x + @template_proc = nil + end + @template = x + end + + + # Defines a the self._format template procedure using + # the template as a string to be interpolated. + def template_proc(template = @template) + return @template_proc if @template_proc + @template_proc = template || '' + # @template_proc = @template_proc.gsub(/[\\"']/) { | x | "\\" + x } + @template_proc = "def self._format; \"#{@template_proc}\"; end" + self.instance_eval @template_proc + @template_proc + end + + + # Formats the current state using the template. + def format + template_proc + _format + end + end + + + # Defaults to ',' + attr_accessor :thousands_separator + + # Defaults to '.' + attr_accessor :decimal_separator + + # If true, insert _thousands_separator_ between each 3 digits in the whole value. + attr_accessor :thousands + + # If true, append _decimal_separator_ and decimal digits after whole value. + attr_accessor :cents + + # If true, prefix value with currency symbol. + attr_accessor :symbol + + # If true, append currency code. + attr_accessor :code + + # If true, append the time. + attr_accessor :time + + # The number of fractional digits in the time. + # Defaults to 4. + attr_accessor :time_fractional_digits + + # If true, use html formatting. + # + # Currency::Money(12.45, :EUR).to_s(:html => true; :code => true) + # => "&#8364;12.45 <span class=\"currency_code\">EUR</span>" + attr_accessor :html + + # A template string used to format a money value. + # Defaults to: + # + # '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}#{time && " "}#{time}' + attr_accessor :template + + # Set the decimal_places + # Defaults to: nil + attr_accessor :decimal_places + + # If passed true, formats for an input field (i.e.: as a number). + def as_input_value=(x) + if x + self.thousands_separator = '' + self.decimal_separator = '.' + self.thousands = false + self.cents = true + self.symbol = false + self.code = false + self.html = false + self.time = false + self.time_fractional_digits = nil + end + x + end + + + @@default = nil + # Get the default Formatter. + def self.default + @@default || self.new + end + + + # Set the default Formatter. + def self.default=(x) + @@default = x + end + + + def initialize(opt = { }) + @thousands_separator = ',' + @decimal_separator = '.' + @thousands = true + @cents = true + @symbol = true + @code = false + @html = false + @time = false + @time_fractional_digits = 4 + @template = '#{code}#{code && " "}#{symbol}#{sign}#{whole}#{fraction}#{time && " "}#{time}' + @template_object = nil + @decimal_places = nil + + opt.each_pair{ | k, v | self.send("#{k}=", v) } + end + + + def currency=(x) # :nodoc: + # DO NOTHING! + end + + + # Sets the template and the Template#template. + def template=(x) + if @template_object + @template_object.template = x + end + @template = x + end + + + # Returns the Template object. + def template_object + return @template_object if @template_object + + @template_object = Template.new + @template_object.template = @template if @template + # $stderr.puts "template.template = #{@template_object.template.inspect}" + @template_object.template_proc # pre-cache before clone. + + @template_object + end + + + def _format(m, currency = nil, time = nil) # :nodoc: + # Get currency. + currency ||= m.currency + + # Get time. + time ||= m.time + + # set decimal places + @decimal_places ||= currency.scale_exp + + # Setup template + tmpl = self.template_object.clone + # $stderr.puts "template.template = #{tmpl.template.inspect}" + tmpl.money = m + tmpl.currency = currency + + # Get scaled integer representation for this Currency. + # $stderr.puts "m.currency = #{m.currency}, currency => #{currency}" + x = m.Money_rep(currency) + + # Remove sign. + x = - x if ( neg = x < 0 ) + tmpl.sign = neg ? '-' : nil + + # Convert to String. + x = x.to_s + + # Keep prefixing "0" until filled to scale. + while ( x.length <= currency.scale_exp ) + x = "0" + x + end + + # Insert decimal place. + whole = x[0 .. currency.format_left] + fraction = x[currency.format_right .. -1] + + # Round the fraction to the supplied number of decimal places + fraction = ((fraction.to_f / currency.scale).round(@decimal_places) * (10 ** @decimal_places)).to_i.to_s + + # Do thousands. + x = whole + if @thousands && (@thousands_separator && ! @thousands_separator.empty?) + x.reverse! + x.gsub!(/(\d\d\d)/) {|y| y + @thousands_separator} + x.sub!(/#{@thousands_separator}$/,'') + x.reverse! + end + + # Put whole and fractional parts. + tmpl.whole = x + tmpl.fraction = @cents && @decimal_separator ? @decimal_separator + fraction : nil + + + # Add symbol? + tmpl.symbol = @symbol ? ((@html && currency.symbol_html) || currency.symbol) : nil + + + # Add currency code. + tmpl.code = @code ? _format_Currency(currency) : nil + + # Add time. + tmpl.time = @time && time ? _format_Time(time) : nil + + # Ask template to format the components. + tmpl.format + end + + + def _format_Currency(c) # :nodoc: + x = '' + x << '<span class="currency_code">' if @html + x << c.code.to_s + x << '</span>' if @html + x + end + + + def _format_Time(t) # :nodoc: + x = '' + x << t.getutc.xmlschema(@time_fractional_digits) if t + x + end + + + @@empty_hash = { } + @@empty_hash.freeze + + # Format a Money object as a String. + # + # m = Money.new("1234567.89") + # m.to_s(:code => true, :symbol => false) + # => "1,234,567.89 USD" + # + def format(m, opt = @@empty_hash) + fmt = self + + unless opt.empty? + fmt = fmt.clone + opt.each_pair{ | k, v | fmt.send("#{k}=", v) } + end + + # $stderr.puts "format(opt = #{opt.inspect})" + fmt._format(m, opt[:currency]) # Allow override of current currency. + end + +end # class + diff --git a/lib/currency/macro.rb b/lib/currency/macro.rb new file mode 100644 index 0000000..263bf3b --- /dev/null +++ b/lib/currency/macro.rb @@ -0,0 +1,321 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +class Currency::Money + @@money_attributes = { } + + # Called by money macro when a money attribute + # is created. + def self.register_money_attribute(attr_opts) + (@@money_attributes[attr_opts[:class]] ||= { })[attr_opts[:attr_name]] = attr_opts + end + + # Returns an array of option hashes for all the money attributes of + # this class. + # + # Superclass attributes are not included. + def self.money_attributes_for_class(cls) + (@@money_atttributes[cls] || { }).values + end + + # Iterates through all known money attributes in all classes. + # + # each_money_attribute { | money_opts | + # ... + # } + def self.each_money_attribute(&blk) + @@money_attributes.each do | cls, hash | + hash.each do | attr_name, attr_opts | + yield attr_opts + end + end + end + +end # class + + +module Currency::Macro + def self.append_features(base) # :nodoc: + # $stderr.puts " Currency::ActiveRecord#append_features(#{base})" + super + base.extend(ClassMethods) + end + + + +# == Macro Suppport +# +# Support for Money attributes. +# +# require 'currency' +# require 'currency/macro' +# +# class SomeClass +# include ::Currency::Macro +# attr_accessor :amount +# attr_money :amount_money, :value => :amount, :currency_fixed => :USD, :rep => :float +# end +# +# x = SomeClass.new +# x.amount = 123.45 +# x.amount +# # => 123.45 +# x.amount_money +# # => $123.45 USD +# x.amount_money = x.amount_money + "12.45" +# # => $135.90 USD +# x.amount +# # => 135.9 +# x.amount = 45.951 +# x.amount_money +# # => $45.95 USD +# x.amount +# # => 45.951 +# + module ClassMethods + + # Defines a Money object attribute that is bound + # to other attributes. + # + # Options: + # + # :value => undef + # + # Defines the value attribute to use for storing the money value. + # Defaults to the attribute name. + # + # If this attribute is different from the attribute name, + # the money object will intercept #{value}=(x) to flush + # any cached Money object. + # + # :readonly => false + # + # If true, the underlying attribute is readonly. Thus the Money object + # cannot be cached. This is useful for computed money values. + # + # :rep => :float + # + # This option specifies how the value attribute stores Money values. + # if :rep is :rep, then the value is stored as a scaled integer as + # defined by the Currency. + # If :rep is :float, or :integer the corresponding #to_f or #to_i + # method is used. + # Defaults to :float. + # + # :currency => undef + # + # Defines the attribute used to store and + # retrieve the Money's Currency 3-letter ISO code. + # + # :currency_fixed => currency_code (e.g.: :USD) + # + # Defines the Currency to use for storing a normalized Money + # value. + # + # All Money values will be converted to this Currency before + # storing. This allows SQL summary operations, + # like SUM(), MAX(), AVG(), etc., to produce meaningful results, + # regardless of the initial currency specified. If this + # option is used, subsequent reads will be in the specified + # normalization :currency_fixed. + # + # :currency_preferred => undef + # + # Defines the name of attribute used to store and + # retrieve the Money's Currency ISO code. This option can be used + # with normalized Money values to retrieve the Money value + # in its original Currency, while + # allowing SQL summary operations on the normalized Money values + # to still be valid. + # + # :currency_update => undef + # + # If true, the currency attribute is updated upon setting the + # money attribute. + # + # :time => undef + # + # Defines the attribute used to + # retrieve the Money's time. If this option is used, each + # Money value will use this attribute during historical Currency + # conversions. + # + # Money values can share a time value with other attributes + # (e.g. a created_on column in ActiveRecord::Base). + # + # If this option is true, the money time attribute will be named + # "#{attr_name}_time" and :time_update will be true. + # + # :time_update => undef + # + # If true, the Money time value is updated upon setting the + # money attribute. + # + def attr_money(attr_name, *opts) + opts = Hash[*opts] + + attr_name = attr_name.to_s + opts[:class] = self + opts[:name] = attr_name.intern + ::Currency::Money.register_money_attribute(opts) + + value = opts[:value] || opts[:name] + opts[:value] = value + write_value = opts[:write_value] ||= "self.#{value} = " + + # Intercept value setter? + if ! opts[:readonly] && value.to_s != attr_name.to_s + alias_accessor = <<-"end_eval" +alias :before_money_#{value}= :#{value}= + +def #{value}=(__value) + @#{attr_name} = nil # uncache + self.before_money_#{value} = __value +end + +end_eval + end + + # How to convert between numeric representation and Money. + rep = opts[:rep] ||= :float + to_rep = opts[:to_rep] + from_rep = opts[:from_rep] + if rep == :rep + to_rep = 'rep' + from_rep = '::Currency::Money.new_rep' + else + case rep + when :float + to_rep = 'to_f' + when :integer + to_rep = 'to_i' + else + raise ::Currency::Exception::InvalidMoneyValue, "Cannot use value representation: #{rep.inspect}" + end + from_rep = '::Currency::Money.new' + end + to_rep = to_rep.to_s + from_rep = from_rep.to_s + + # Money time values. + time = opts[:time] + write_time = '' + if time + if time == true + time = "#{attr_name}_time" + opts[:time_update] = true + end + read_time = "self.#{time}" + end + opts[:time] = time + if opts[:time_update] + write_time = "self.#{time} = #{attr_name}_money && #{attr_name}_money.time" + end + time ||= 'nil' + read_time ||= time + + currency_fixed = opts[:currency_fixed] + currency_fixed &&= ":#{currency_fixed}" + + currency = opts[:currency] + if currency == true + currency = currency.to_s + currency = "self.#{attr_name}_currency" + end + if currency + read_currency = "self.#{currency}" + if opts[:currency_update] + write_currency = "self.#{currency} = #{attr_name}_money.nil? ? nil : #{attr_name}_money.currency.code" + else + convert_currency = "#{attr_name}_money = #{attr_name}_money.convert(#{read_currency}, #{read_time})" + end + end + opts[:currency] = currency + write_currency ||= '' + convert_currency ||= '' + + currency_preferred = opts[:currency_preferred] + if currency_preferred + currency_preferred = currency_preferred.to_s + read_preferred_currency = "@#{attr_name} = @#{attr_name}.convert(#{currency_preferred}, #{read_time})" + write_preferred_currency = "self.#{currency_preferred} = @#{attr_name}_money.currency.code" + end + + currency ||= currency_fixed + read_currency ||= currency + + alias_accessor ||= '' + + validate ||= '' + + if opts[:readonly] + eval_opts = [ (opts[:module_eval] = x = <<-"end_eval"), __FILE__, __LINE__ ] +#{validate} + +def #{attr_name} + #{attr_name}_rep = #{value} + if #{attr_name}_rep != nil + #{attr_name} = #{from_rep}(#{attr_name}_rep, #{read_currency} || #{currency}, #{read_time} || #{time}) + #{read_preferred_currency} + else + #{attr_name} = nil + end + #{attr_name} +end + +end_eval + else + eval_opts = [ (opts[:module_eval] = x = <<-"end_eval"), __FILE__, __LINE__ ] +#{validate} + +#{alias_accessor} + +def #{attr_name} + unless @#{attr_name} + #{attr_name}_rep = #{value} + if #{attr_name}_rep != nil + @#{attr_name} = #{from_rep}(#{attr_name}_rep, #{read_currency} || #{currency}, #{read_time} || #{time}) + #{read_preferred_currency} + end + end + @#{attr_name} +end + + +def #{attr_name}=(value) + if value == nil + #{attr_name}_money = nil + elsif value.kind_of?(Integer) || value.kind_of?(Float) || value.kind_of?(String) + #{attr_name}_money = ::Currency.Money(value, #{read_currency}, #{read_time}) + #{write_preferred_currency} + elsif value.kind_of?(::Currency::Money) + #{attr_name}_money = value + #{write_preferred_currency} + #{convert_currency} + else + raise ::Currency::Exception::InvalidMoneyValue, value + end + + @#{attr_name} = #{attr_name}_money + #{write_value}(#{attr_name}_money.nil? ? nil : #{attr_name}_money.#{to_rep}) + #{write_currency} + #{write_time} + + value +end + +end_eval + end + + # $stderr.puts " CODE = #{x}" + module_eval(*eval_opts) + end + end # module +end # module + + +# Use include ::Currency::Macro +#::Object.class_eval do +# include Currency::Macro +#end + diff --git a/lib/currency/money.rb b/lib/currency/money.rb new file mode 100644 index 0000000..c6c5952 --- /dev/null +++ b/lib/currency/money.rb @@ -0,0 +1,295 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +# +# Represents an amount of money in a particular currency. +# +# A Money object stores its value using a scaled Integer representation +# and a Currency object. +# +# A Money object also has a time, which is used in conversions +# against historical exchange rates. +# +class Currency::Money + include Comparable + + @@default_time = nil + def self.default_time + @@default_time + end + def self.default_time=(x) + @@default_time = x + end + + @@empty_hash = { } + @@empty_hash.freeze + + # + # DO NOT CALL THIS DIRECTLY: + # + # See Currency.Money() function. + # + # Construct a Money value object + # from a pre-scaled external representation: + # where x is a Float, Integer, String, etc. + # + # If a currency is not specified, Currency.default is used. + # + # x.Money_rep(currency) + # + # is invoked to coerce x into a Money representation value. + # + # For example: + # + # 123.Money_rep(:USD) => 12300 + # + # Because the USD Currency object has a #scale of 100 + # + # See #Money_rep(currency) mixin. + # + def initialize(x, currency = nil, time = nil) + opts ||= @@empty_hash + + # Set ivars. + currency = ::Currency::Currency.get(currency) + @currency = currency + @time = time || ::Currency::Money.default_time + @time = ::Currency::Money.now if @time == :now + if x.kind_of?(String) + if currency + m = currency.parser_or_default.parse(x, :currency => currency) + else + m = ::Currency::Parser.default.parse(x) + end + @currency = m.currency unless @currency + @time = m.time if m.time + @rep = m.rep + else + @currency = ::Currency::Currency.default unless @currency + @rep = x.Money_rep(@currency) + end + + end + + # Returns a Time.new + # Can be modifed for special purposes. + def self.now + Time.new + end + + # Compatibility with Money package. + def self.us_dollar(x) + self.new(x, :USD) + end + + + # Compatibility with Money package. + def cents + @rep + end + + + # Construct from post-scaled internal representation. + def self.new_rep(r, currency = nil, time = nil) + x = self.new(0, currency, time) + x.set_rep(r) + x + end + + + # Construct from post-scaled internal representation. + # using the same currency. + # + # x = Currency.Money("1.98", :USD) + # x.new_rep(123) => USD $1.23 + # + # time defaults to self.time. + def new_rep(r, time = nil) + time ||= @time + x = self.class.new(0, @currency, time) + x.set_rep(r) + x + end + + # Do not call this method directly. + # CLIENTS SHOULD NEVER CALL set_rep DIRECTLY. + # You have been warned in ALL CAPS. + def set_rep(r) # :nodoc: + r = r.to_i unless r.kind_of?(Integer) + @rep = r + end + + # Do not call this method directly. + # CLIENTS SHOULD NEVER CALL set_time DIRECTLY. + # You have been warned in ALL CAPS. + def set_time(time) # :nodoc: + @time = time + end + + # Returns the Money representation (usually an Integer). + def rep + @rep + end + + # Get the Money's Currency. + def currency + @currency + end + + # Get the Money's time. + def time + @time + end + + # Convert Money to another Currency. + # currency can be a Symbol or a Currency object. + # If currency is nil, the Currency.default is used. + def convert(currency, time = nil) + currency = ::Currency::Currency.default if currency.nil? + currency = ::Currency::Currency.get(currency) unless currency.kind_of?(Currency) + if @currency == currency + self + else + time = self.time if time == :money + ::Currency::Exchange::Rate::Source.current.convert(self, currency, time) + end + end + + + # Hash for hash table: both value and currency. + # See #eql? below. + def hash + @rep.hash ^ @currency.hash + end + + + # True if money values have the same value and currency. + def eql?(x) + self.class == x.class && + @rep == x.rep && + @currency == x.currency + end + + # True if money values have the same value and currency. + def ==(x) + self.class == x.class && + @rep == x.rep && + @currency == x.currency + end + + # Compares Money values. + # Will convert x to self.currency before comparision. + def <=>(x) + if @currency == x.currency + @rep <=> x.rep + else + @rep <=> convert(@currency, @time).rep + end + end + + + # - Money => Money + # + # Negates a Money value. + def -@ + new_rep(- @rep) + end + + # Money + (Money | Number) => Money + # + # Right side may be coerced to left side's Currency. + def +(x) + new_rep(@rep + x.Money_rep(@currency)) + end + + # Money - (Money | Number) => Money + # + # Right side may be coerced to left side's Currency. + def -(x) + new_rep(@rep - x.Money_rep(@currency)) + end + + # Money * Number => Money + # + # Right side must be Number. + def *(x) + new_rep(@rep * x) + end + + # Money / Money => Float (ratio) + # Money / Number => Money + # + # Right side must be Money or Number. + # Right side Integers are not coerced to Float before + # division. + def /(x) + if x.kind_of?(self.class) + (@rep.to_f) / (x.Money_rep(@currency).to_f) + else + new_rep(@rep / x) + end + end + + # Formats the Money value as a String using the Currency's Formatter. + def format(*opt) + @currency.format(self, *opt) + end + + # Formats the Money value as a String. + def to_s(*opt) + @currency.format(self, *opt) + end + + # Coerces the Money's value to a Float. + # May cause loss of precision. + def to_f + Float(@rep) / @currency.scale + end + + # Coerces the Money's value to an Integer. + # May cause loss of precision. + def to_i + @rep / @currency.scale + end + + # True if the Money's value is zero. + def zero? + @rep == 0 + end + + # True if the Money's value is greater than zero. + def positive? + @rep > 0 + end + + # True if the Money's value is less than zero. + def negative? + @rep < 0 + end + + # Returns the Money's value representation in another currency. + def Money_rep(currency, time = nil) + # Attempt conversion? + if @currency != currency || (time && @time != time) + self.convert(currency, time).rep + # raise ::Currency::Exception::Generic, "Incompatible Currency: #{@currency} != #{currency}" + else + @rep + end + end + + # Basic inspection, with symbol, currency code and time. + # The standard #inspect method is available as #inspect_deep. + def inspect(*opts) + self.format(:symbol => true, :code => true, :time => true) + end + + # How to alias a method defined in an object superclass in a different class: + define_method(:inspect_deep, Object.instance_method(:inspect)) + # How call a method defined in a superclass from a method with a different name: + # def inspect_deep(*opts) + # self.class.superclass.instance_method(:inspect).bind(self).call + # end + +end # class + diff --git a/lib/currency/money_helper.rb b/lib/currency/money_helper.rb new file mode 100644 index 0000000..015b4c0 --- /dev/null +++ b/lib/currency/money_helper.rb @@ -0,0 +1,13 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +module ActionView::Helpers::MoneyHelper + # Creates a suitable HTML element for a Money value field. + def money_field(object, method, options = {}) + InstanceTag.new(object, method, self).to_input_field_tag("text", options) + end +end + + +ActionView::Base.load_helper(File.dirname(__FILE__)) + diff --git a/lib/currency/parser.rb b/lib/currency/parser.rb new file mode 100644 index 0000000..2f70990 --- /dev/null +++ b/lib/currency/parser.rb @@ -0,0 +1,193 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + + +require 'rss/rss' # Time#xmlschema + + +# This class parses a Money value from a String. +# Each Currency has a default Parser. +class Currency::Parser + + # The default Currency to use if no Currency is specified. + attr_accessor :currency + + # If true and a parsed string contains a ISO currency code + # that is not the same as currency, + # #parse() will raise IncompatibleCurrency. + # Defaults to false. + attr_accessor :enforce_currency + + # The default Time to use if no Time is specified in the string. + # If :now, time is set to Time.new. + attr_accessor :time + + @@default = nil + # Get the default Formatter. + def self.default + @@default ||= + self.new + end + + + # Set the default Formatter. + def self.default=(x) + @@default = x + end + + + def initialize(opt = { }) + @time = + @enforce_currency = + @currency = + nil + opt.each_pair{ | k, v | self.send("#{k}=", v) } + end + + + def _parse(str) # :nodoc: + x = str + + # Get currency. + # puts "str = #{str.inspect}, @currency = #{@currency}" + + md = nil # match data + + # $stderr.puts "'#{x}'.Money_rep(#{self})" + + # Parse time. + time = nil + if (md = /(\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z)/.match(x)) + time = Time.xmlschema(md[1]) + unless time + raise Currency::Exception::InvalidMoneyString, + [ + "time: #{str.inspect} #{currency} #{x.inspect}", + :string, str, + :currency, currency, + :state, x, + ] + end + x = md.pre_match + md.post_match + end + # Default time + time ||= @time + time = Time.new if time == :now + + # $stderr.puts "x = #{x}" + convert_currency = nil + # Handle currency code in string. + if (md = /([A-Z][A-Z][A-Z])/.match(x)) + curr = ::Currency::Currency.get(md[1]) + x = md.pre_match + md.post_match + if @currency && @currency != curr + if @enforce_currency + raise ::Currency::Exception::IncompatibleCurrency, + [ + "currency: #{str.inspect} #{@currency.code}", + :string, str, + :default_currency, @currency, + :parsed_currency, curr, + ] + end + convert_currency = @currency + end + currency = curr + else + currency = @currency || ::Currency::Currency.default + currency = ::Currency::Currency.get(currency) + end + + # Remove placeholders and symbol. + x = x.gsub(/[, ]/, '') + symbol = currency.symbol # FIXME + x = x.gsub(symbol, '') if symbol + + # $stderr.puts "x = #{x.inspect}" + # Match: whole Currency value. + if md = /^([-+]?\d+)\.?$/.match(x) + # $stderr.puts "'#{self}'.parse(#{str}) => EXACT" + x = ::Currency::Money.new_rep(md[1].to_i * currency.scale, currency, @time) + + # Match: fractional Currency value. + elsif md = /^([-+]?)(\d*)\.(\d+)$/.match(x) + sign = md[1] + whole = md[2] + part = md[3] + + # $stderr.puts "'#{self}'.parse(#{str}) => DECIMAL (#{sign} #{whole} . #{part})" + + if part.length != currency.scale + + # Pad decimal places with additional '0' + while part.length < currency.scale_exp + part << '0' + end + + # Truncate to Currency's decimal size. + part = part[0 ... currency.scale_exp] + + # $stderr.puts " => INEXACT DECIMAL '#{whole}'" + end + + # Put the string back together: + # #{sign}#{whole}#{part} + whole = sign + whole + part + # $stderr.puts " => REP = #{whole}" + + x = whole.to_i + + x = ::Currency::Money.new_rep(x, currency, time) + else + # $stderr.puts "'#{self}'.parse(#{str}) => ??? '#{x}'" + #x.to_f.Money_rep(self) + raise ::Currency::Exception::InvalidMoneyString, + [ + "#{str.inspect} #{currency} #{x.inspect}", + :string, str, + :currency, currency, + :state, x, + ] + end + + # Do conversion. + if convert_currency + x = x.convert(convert_currency) + end + + + x + end + + + @@empty_hash = { } + @@empty_hash.freeze + + # Parse a Money string in this Currency. + # + # "123.45".money # Using default Currency. + # => USD $123.45 + # + # "$123.45 USD".money # Explicit Currency. + # => USD $123.45 + # + # "CAD 123.45".money + # => CAD $123.45 + # + # "123.45 CAD".money(:USD) # Incompatible explicit Currency. + # !!! "123.45 CAD" USD (Currency::Exception::IncompatibleCurrency) + # + def parse(str, opt = @@empty_hash) + prs = self + + unless opt.empty? + prs = prs.clone + opt.each_pair{ | k, v | prs.send("#{k}=", v) } + end + + prs._parse(str) + end + +end # class + + diff --git a/test/ar_column_test.rb b/test/ar_column_test.rb new file mode 100644 index 0000000..bf8acb3 --- /dev/null +++ b/test/ar_column_test.rb @@ -0,0 +1,69 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/ar_test_core' +require 'currency' + +require 'rubygems' +require 'active_record' +require 'active_record/migration' +require 'currency/active_record' + +module Currency + +class ArFieldTest < ArTestCore + + ################################################## + # Basic CurrenyTest AR::B class + # + + TABLE_NAME = 'currency_column_test' + + class CurrencyColumnTestMigration < AR_M + def self.up + create_table TABLE_NAME.intern do |t| + t.column :name, :string + t.column :amount, :integer # Money + t.column :amount_currency, :string, :size => 3 # Money.currency.code + end + end + + def self.down + drop_table TABLE_NAME.intern + end + end + + class CurrencyColumnTest < AR_B + set_table_name TABLE_NAME + attr_money :amount, :currency_column => true + end + + ################################################## + + def setup + @currency_test_migration ||= CurrencyColumnTestMigration + @currency_test ||= CurrencyColumnTest + super + end + + def teardown + super + end + + ################################################## + + + def test_field + insert_records + + assert_not_nil usd = @currency_test.find(@usd.id) + assert_equal_currency usd, @usd + + assert_not_nil cad = @currency_test.find(@cad.id) + assert_equal_currency cad, @cad + end + +end + +end # module + diff --git a/test/ar_simple_test.rb b/test/ar_simple_test.rb new file mode 100644 index 0000000..148da26 --- /dev/null +++ b/test/ar_simple_test.rb @@ -0,0 +1,31 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/ar_test_core' +require 'currency' + +require 'rubygems' +require 'active_record' +require 'active_record/migration' +require 'currency/active_record' + +module Currency + +class ArSimpleTest < ArTestCore + + def test_simple + insert_records + + assert_not_nil usd = @currency_test.find(@usd.id) + assert_equal_currency usd, @usd + + assert_not_nil cad = @currency_test.find(@cad.id) + assert_equal_money cad, @cad + + assert_equal cad.amount.currency.code, :USD + end + +end + +end # module + diff --git a/test/ar_test_base.rb b/test/ar_test_base.rb new file mode 100644 index 0000000..efbac5f --- /dev/null +++ b/test/ar_test_base.rb @@ -0,0 +1,151 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/test_base' +require 'currency' + +require 'rubygems' +require 'active_record' +require 'active_record/migration' +require 'currency/active_record' + +AR_M = ActiveRecord::Migration +AR_B = ActiveRecord::Base + +module Currency + +class ArTestBase < TestBase + + ################################################## + + def setup + super + AR_B.establish_connection(database_spec) + + # Subclasses can override this. + @currency_test_migration ||= nil + @currency_test ||= nil + + # schema_down + + schema_up + end + + + def teardown + super + # schema_down + end + + + def database_spec + # TODO: Get from ../config/database.yml:test + # Create test database on: + + # MYSQL: + # + # sudo mysqladmin create test; + # sudo mysql + # grant all on test.* to test@localhost identified by 'test'; + # flush privileges; + + # POSTGRES: + # + # CREATE USER test PASSWORD 'test'; + # CREATE DATABASE test WITH OWNER = test; + # + + @database_spec = { + :adapter => ENV['TEST_DB_ADAPTER'] || 'mysql', + :host => ENV['TEST_DB_HOST'] || 'localhost', + :username => ENV['TEST_DB_USER'] || 'test', + :password => ENV['TEST_DB_PASS'] || 'test', + :database => ENV['TEST_DB_TEST'] || 'test' + } + end + + + def schema_up + return unless @currency_test_migration + begin + @currency_test_migration.migrate(:up) + rescue Object =>e + $stderr.puts "Warning: #{e}" + end + end + + + def schema_down + return unless @currency_test_migration + begin + @currency_test_migration.migrate(:down) + rescue Object => e + $stderr.puts "Warning: #{e}" + end + end + + + ################################################## + # Scaffold + # + + def insert_records + delete_records + + @currency_test.reset_column_information + + @usd = @currency_test.new(:name => '#1: USD', :amount => Money.new("12.34", :USD)) + @usd.save + + @cad = @currency_test.new(:name => '#2: CAD', :amount => Money.new("56.78", :CAD)) + @cad.save + end + + + def delete_records + @currency_test.destroy_all + end + + + ################################################## + + + def assert_equal_money(a,b) + assert_not_nil a + assert_not_nil b + # Make sure a and b are not the same object. + assert_not_equal a.object_id, b.object_id + assert_equal a.id, b.id + assert_not_nil a.amount + assert_kind_of Money, a.amount + assert_not_nil b.amount + assert_kind_of Money, b.amount + # Make sure that what gets stored in the database comes back out + # when converted back to the original currency. + assert_equal a.amount.convert(b.amount.currency).rep, b.amount.rep + end + + + def assert_equal_currency(a,b) + assert_equal_money a, b + + assert_equal a.amount.rep, b.amount.rep + assert_equal a.amount.currency, b.amount.currency + assert_equal a.amount.currency.code, b.amount.currency.code + + end + + + ################################################## + # + # + + + def test_dummy + + end + +end + +end # module + diff --git a/test/ar_test_core.rb b/test/ar_test_core.rb new file mode 100644 index 0000000..324cc5f --- /dev/null +++ b/test/ar_test_core.rb @@ -0,0 +1,64 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/ar_test_base' + +module Currency + +class ArTestCore < ArTestBase + + ################################################## + # Basic CurrenyTest AR::B class + # + + TABLE_NAME = 'currency_test' + + class CurrencyTestMigration < AR_M + def self.up + create_table TABLE_NAME.intern do |t| + t.column :name, :string + t.column :amount, :integer # Money + end + end + + def self.down + drop_table TABLE_NAME.intern + end + end + + + class CurrencyTest < AR_B + set_table_name TABLE_NAME + attr_money :amount + end + + + ################################################## + + + def setup + @currency_test_migration ||= CurrencyTestMigration + @currency_test ||= CurrencyTest + super + end + + + def teardown + super + # schema_down + end + + + ################################################## + # + # + + + def test_insert + insert_records + end + +end + +end # module + diff --git a/test/config_test.rb b/test/config_test.rb new file mode 100644 index 0000000..1024747 --- /dev/null +++ b/test/config_test.rb @@ -0,0 +1,36 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + + +require 'test/test_base' +require 'currency' + +module Currency + +class ConfigTest < TestBase + def setup + super + end + + ############################################ + # Simple stuff. + # + + def test_config + assert_kind_of Money, m = Money.new(1.999) + assert_equal 199, m.rep + + Config.configure do | c | + c.float_ref_filter = Proc.new { | x | x.round } + + assert_kind_of Money, m = Money.new(1.999) + assert_equal 200, m.rep + end + + end + +end # class + +end # module + + diff --git a/test/federal_reserve_test.rb b/test/federal_reserve_test.rb new file mode 100644 index 0000000..a4aa4c9 --- /dev/null +++ b/test/federal_reserve_test.rb @@ -0,0 +1,75 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/test_base' + +require 'currency' # For :type => :money +require 'currency/exchange/rate/source/federal_reserve' + +module Currency + +class FederalReserveTest < TestBase + def setup + super + end + + + @@available = nil + + # New York Fed rates are not available on Saturday and Sunday. + def available? + if @@available == nil + @@available = @source.available? + STDERR.puts "Warning: FederalReserve unavailable on Saturday and Sunday, skipping tests." unless @@available + end + @@available + end + + + def get_rate_source + # Force FederalReserve Exchange. + verbose = false + source = @source = Exchange::Rate::Source::FederalReserve.new(:verbose => verbose) + deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) + end + + + + def test_usd_cad + return unless available? + + # yesterday = Time.now.to_date - 1 + + assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates + #assert_not_nil rates[:USD] + #assert_not_nil usd_cad = rates[:USD][:CAD] + + assert_not_nil usd = Money.new(123.45, :USD) + assert_not_nil cad = usd.convert(:CAD) + + # assert_kind_of Numeric, m = (cad.to_f / usd.to_f) + # $stderr.puts "m = #{m}" + # assert_equal_float usd_cad, m, 0.001 + end + + + def test_cad_eur + return unless available? + + assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates + #assert_not_nil rates[:USD] + #assert_not_nil usd_cad = rates[:USD][:CAD] + #assert_not_nil usd_eur = rates[:USD][:EUR] + + assert_not_nil cad = Money.new(123.45, :CAD) + assert_not_nil eur = cad.convert(:EUR) + + #assert_kind_of Numeric, m = (eur.to_f / cad.to_f) + # $stderr.puts "m = #{m}" + #assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 + end + +end + +end # module + diff --git a/test/formatter_test.rb b/test/formatter_test.rb new file mode 100644 index 0000000..c9e2b99 --- /dev/null +++ b/test/formatter_test.rb @@ -0,0 +1,92 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/test_base' +require 'currency' + +module Currency + +class FormatterTest < TestBase + def setup + super + end + + ############################################ + # Simple stuff. + # + + def test_default(time = nil) + assert_kind_of Money, m = ::Currency::Money.new_rep(123456789, :USD, time) + assert_equal Currency.default, m.currency + assert_equal :USD, m.currency.code + assert_equal "$1,234,567.89", m.to_s + assert_equal time, m.time + + m + end + + + def test_thousands + m = test_default + assert_equal "$1234567.89", m.to_s(:thousands => false) + assert_equal "$1,234,567.89", m.to_s(:thousands => true) + + m + end + + + def test_cents + m = test_default + assert_equal "$1,234,567", m.to_s(:cents => false) + assert_equal "$1,234,567.89", m.to_s(:cents => true) + + m + end + + + def test_symbol + m = test_default + assert_equal "1,234,567.89", m.to_s(:symbol => false) + assert_equal "$1,234,567.89", m.to_s(:symbol => true) + + m + end + + + def test_code + m = test_default + assert_equal "$1,234,567.89", m.to_s(:code => false) + assert_equal "USD $1,234,567.89", m.to_s(:code => true) + + m + end + + + def test_misc + m = ::Currency::Money(12.45, :USD) + assert_equal "<span class=\"currency_code\">USD</span> $12.45", + m.to_s(:html => true, :code => true) + + m = ::Currency::Money(12.45, :EUR) + assert_equal "<span class=\"currency_code\">EUR</span> &#8364;12.45", + m.to_s(:html => true, :code => true) + + m = ::Currency::Money(12345.45, :EUR) + assert_equal "<span class=\"currency_code\">EUR</span> &#8364;12_345.45", + m.to_s(:html => true, :code => true, :thousands_separator => '_') + end + + + def test_time + time = Time.new + m = test_default(time) + assert_equal "$1,234,567.89", m.to_s(:time => false) + assert_equal "$1,234,567.89 #{time.getutc.xmlschema(4)}", m.to_s(:time => true) + + m + end + +end + +end # module + diff --git a/test/historical_writer_test.rb b/test/historical_writer_test.rb new file mode 100644 index 0000000..3ae739b --- /dev/null +++ b/test/historical_writer_test.rb @@ -0,0 +1,187 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/ar_test_base' + +require 'rubygems' +require 'active_record' +require 'active_record/migration' + +require 'currency' # For :type => :money + +require 'currency/exchange/rate/source/historical' +require 'currency/exchange/rate/source/historical/writer' +require 'currency/exchange/rate/source/xe' +require 'currency/exchange/rate/source/new_york_fed' + + +module Currency + +class HistoricalWriterTest < ArTestBase + + RATE_CLASS = Exchange::Rate::Source::Historical::Rate + TABLE_NAME = RATE_CLASS.table_name + + class HistoricalRateMigration < AR_M + def self.up + RATE_CLASS.__create_table(self) + end + + def self.down + drop_table TABLE_NAME.intern + end + end + + + def initialize(*args) + @currency_test_migration = HistoricalRateMigration + super + + @src = Exchange::Rate::Source::Xe.new + @src2 = Exchange::Rate::Source::NewYorkFed.new + end + + + def setup + super + + end + + + def test_writer + assert_not_nil src = @src + assert_not_nil writer = Exchange::Rate::Source::Historical::Writer.new() + writer.time_quantitizer = :current + writer.required_currencies = [ :USD, :GBP, :EUR, :CAD ] + writer.base_currencies = [ :USD ] + writer.preferred_currencies = writer.required_currencies + writer.reciprocal_rates = true + writer.all_rates = true + writer.identity_rates = false + + writer + end + + + def writer_src + writer = test_writer + writer.source = @src + rates = writer.write_rates + assert_not_nil rates + assert rates.size > 0 + assert 12, rates.size + assert_h_rates(rates, writer) + end + + + def writer_src2 + writer = test_writer + writer.source = @src2 + return unless writer.source.available? + rates = writer.write_rates + assert_not_nil rates + assert rates.size > 0 + assert_equal 12, rates.size + assert_h_rates(rates, writer) + end + + + def xxx_test_required_failure + assert_not_nil writer = Exchange::Rate::Source::Historical::Writer.new() + assert_not_nil src = @src + writer.source = src + writer.required_currencies = [ :USD, :GBP, :EUR, :CAD, :ZZZ ] + writer.preferred_currencies = writer.required_currencies + assert_raises(::RuntimeError) { writer.selected_rates } + end + + + def test_historical_rates + # Make sure there are historical Rates avail for today. + writer_src + writer_src2 + + # Force Historical Rate Source. + source = Exchange::Rate::Source::Historical.new + deriver = Exchange::Rate::Deriver.new(:source => source) + Exchange::Rate::Source.default = deriver + + assert_not_nil rates = source.get_raw_rates + assert ! rates.empty? + # $stderr.puts "historical rates = #{rates.inspect}" + + assert_not_nil rates = source.get_rates + assert ! rates.empty? + # $stderr.puts "historical rates = #{rates.inspect}" + + assert_not_nil m_usd = ::Currency.Money('1234.56', :USD, :now) + # $stderr.puts "m_usd = #{m_usd.to_s(:code => true)}" + assert_not_nil m_eur = m_usd.convert(:EUR) + # $stderr.puts "m_eur = #{m_eur.to_s(:code => true)}" + + end + + + def assert_h_rates(rates, writer = nil) + assert_not_nil hr0 = rates[0] + rates.each do | hr | + found_hr = nil + begin + assert_not_nil found_hr = hr.find_matching_this(:first) + rescue Object => err + raise "#{hr.inspect}: #{err}:\n#{err.backtrace.inspect}" + end + + assert_not_nil hr0 + + assert_equal hr0.date, hr.date + assert_equal hr0.date_0, hr.date_0 + assert_equal hr0.date_1, hr.date_1 + assert_equal hr0.source, hr.source + + assert_equal_rate(hr, found_hr) + assert_rate_defaults(hr, writer) + end + end + + + def assert_equal_rate(hr0, hr) + assert_equal hr0.c1.to_s, hr.c1.to_s + assert_equal hr0.c2.to_s, hr.c2.to_s + assert_equal hr0.source, hr.source + assert_equal_float hr0.rate, hr.rate + assert_equal_float hr0.rate_avg, hr.rate_avg + assert_equal hr0.rate_samples, hr.rate_samples + assert_equal_float hr0.rate_lo, hr.rate_lo + assert_equal_float hr0.rate_hi, hr.rate_hi + assert_equal_float hr0.rate_date_0, hr.rate_date_0 + assert_equal_float hr0.rate_date_1, hr.rate_date_1 + assert_equal hr0.date, hr.date + assert_equal hr0.date_0, hr.date_0 + assert_equal hr0.date_1, hr.date_1 + assert_equal hr0.derived, hr.derived + end + + + def assert_rate_defaults(hr, writer) + assert_equal writer.source.name, hr.source if writer + assert_equal hr.rate, hr.rate_avg + assert_equal hr.rate_samples, 1 + assert_equal hr.rate, hr.rate_lo + assert_equal hr.rate, hr.rate_hi + assert_equal hr.rate, hr.rate_date_0 + assert_equal hr.rate, hr.rate_date_1 + end + + + def assert_equal_float(x1, x2, eps = 0.00001) + eps = (x1 * eps).abs + assert((x1 - eps) <= x2) + assert((x1 + eps) >= x2) + end + + +end + +end # module + diff --git a/test/macro_test.rb b/test/macro_test.rb new file mode 100644 index 0000000..d23076d --- /dev/null +++ b/test/macro_test.rb @@ -0,0 +1,109 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/test_base' +require 'currency' +require 'currency/macro' + +module Currency + +class MacroTest < TestBase + class Record + include ::Currency::Macro + + attr_accessor :date + attr_accessor :gross + attr_accessor :tax + attr_accessor :net + attr_accessor :currency + + attr_money :gross_money, :value => :gross, :time => :date, :currency => :currency + attr_money :tax_money, :value => :tax, :time => :date, :currency => :currency + attr_money :net_money, :value => :net, :time => :date, :currency => :currency + + def initialize + self.date = Time.now + self.currency = :USD + end + + def compute_net + self.net = self.gross - self.tax + end + + def compute_net_money + self.net_money = self.gross_money - self.tax_money + end + + end + + def setup + super + end + + ############################################ + # Tests + # + + def test_read_money + assert_kind_of Record, r = Record.new + assert_not_nil r.gross = 10.00 + assert_equal r.gross_money.to_f, r.gross + assert_equal r.gross_money.currency.code, r.currency + assert_equal r.gross_money.time, r.date + + r + end + + + def test_write_money_rep + assert_kind_of Record, r = Record.new + assert_not_nil r.gross_money = 10.00 + assert_equal r.gross_money.to_f, r.gross + assert_equal r.gross_money.currency.code, r.currency + assert_equal r.gross_money.time, r.date + + r + end + + + def test_money_cache + r = test_read_money + + assert_not_nil r_gross = r.gross + assert r_gross.object_id == r.gross.object_id + + # Cache flush + assert_not_nil r.gross = 12.00 + assert_equal r.gross_money.to_f, r.gross + assert r_gross.object_id != r.gross.object_id + end + + + def test_currency + r = test_read_money + + assert_not_nil r.gross_money.currency + assert_equal r.gross_money.currency.code, r.currency + + end + + + def test_compute + assert_kind_of Record, r = Record.new + assert_not_nil r.gross = 10.00 + assert_not_nil r.tax = 1.50 + r.compute_net + + assert_equal 8.50, r.net + assert_equal r.net, r.net_money.to_f + + r.compute_net_money + + assert_equal 8.50, r.net + assert_equal r.net, r.net_money.to_f + end + +end # class + +end # module + diff --git a/test/money_test.rb b/test/money_test.rb new file mode 100644 index 0000000..050ef3f --- /dev/null +++ b/test/money_test.rb @@ -0,0 +1,301 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + + +require 'test/test_base' +require 'currency' + +module Currency + +class MoneyTest < TestBase + def setup + super + end + + ############################################ + # Simple stuff. + # + + def test_create + assert_kind_of Money, m = Money.new(1.99) + assert_equal m.currency, Currency.default + assert_equal m.currency.code, :USD + + m + end + + def test_object_money_method + assert_kind_of Money, m = 1.99.money(:USD) + assert_equal m.currency.code, :USD + assert_equal m.rep, 199 + + assert_kind_of Money, m = 199.money(:CAD) + assert_equal m.currency.code, :CAD + assert_equal m.rep, 19900 + + assert_kind_of Money, m = "13.98".money(:CAD) + assert_equal m.currency.code, :CAD + assert_equal m.rep, 1398 + + assert_kind_of Money, m = "45.99".money(:EUR) + assert_equal m.currency.code, :EUR + assert_equal m.rep, 4599 + end + + def test_zero + m = Money.new(0) + assert ! m.negative? + assert m.zero? + assert ! m.positive? + m + end + + def test_negative + m = Money.new(-1.00, :USD) + assert m.negative? + assert ! m.zero? + assert ! m.positive? + m + end + + def test_positive + m = Money.new(2.99, :USD) + assert ! m.negative? + assert ! m.zero? + assert m.positive? + m + end + + def test_relational + n = test_negative + z = test_zero + p = test_positive + + assert (n < p) + assert ! (n > p) + assert ! (p < n) + assert (p > n) + assert (p != n) + + assert (z <= z) + assert (z >= z) + + assert (z <= p) + assert (n <= z) + assert (z >= n) + + assert n == n + assert p == p + + assert z == test_zero + end + + def test_compare + n = test_negative + z = test_zero + p = test_positive + + assert (n <=> p) == -1 + assert (p <=> n) == 1 + assert (p <=> z) == 1 + + assert (n <=> n) == 0 + assert (z <=> z) == 0 + assert (p <=> p) == 0 + end + + def test_rep + assert_not_nil m = Money.new(123, :USD) + assert m.rep == 12300 + + assert_not_nil m = Money.new(123.45, :USD) + assert m.rep == 12345 + + assert_not_nil m = Money.new("123.456", :USD) + assert m.rep == 12345 + end + + def test_convert + assert_not_nil m = Money.new("123.456", :USD) + assert m.rep == 12345 + + assert_equal 123, m.to_i + assert_equal 123.45, m.to_f + assert_equal "$123.45", m.to_s + end + + def test_eql + assert_not_nil usd1 = Money.new(123, :USD) + assert_not_nil usd2 = Money.new("123", :USD) + + assert_equal :USD, usd1.currency.code + assert_equal :USD, usd2.currency.code + + assert_equal usd1.rep, usd2.rep + + assert usd1 == usd2 + + end + + def test_not_eql + + assert_not_nil usd1 = Money.new(123, :USD) + assert_not_nil usd2 = Money.new("123.01", :USD) + + assert_equal :USD, usd1.currency.code + assert_equal :USD, usd2.currency.code + + assert_not_equal usd1.rep, usd2.rep + + assert usd1 != usd2 + + ################ + # currency != + # rep == + + assert_not_nil usd = Money.new(123, :USD) + assert_not_nil cad = Money.new(123, :CAD) + + assert_equal :USD, usd.currency.code + assert_equal :CAD, cad.currency.code + + assert_equal usd.rep, cad.rep + assert usd.currency != cad.currency + + assert usd != cad + + end + + def test_op + # Using default get_rate + assert_not_nil usd = Money.new(123.45, :USD) + assert_not_nil cad = Money.new(123.45, :CAD) + + # - Money => Money + assert_equal(-12345, (- usd).rep) + assert_equal :USD, (- usd).currency.code + + assert_equal(-12345, (- cad).rep) + assert_equal :CAD, (- cad).currency.code + + # Money + Money => Money + assert_kind_of Money, m = (usd + usd) + assert_equal 24690, m.rep + assert_equal :USD, m.currency.code + + assert_kind_of Money, m = (usd + cad) + assert_equal 22889, m.rep + assert_equal :USD, m.currency.code + + assert_kind_of Money, m = (cad + usd) + assert_equal 26798, m.rep + assert_equal :CAD, m.currency.code + + # Money - Money => Money + assert_kind_of Money, m = (usd - usd) + assert_equal 0, m.rep + assert_equal :USD, m.currency.code + + assert_kind_of Money, m = (usd - cad) + assert_equal 1801, m.rep + assert_equal :USD, m.currency.code + + assert_kind_of Money, m = (cad - usd) + assert_equal -2108, m.rep + assert_equal :CAD, m.currency.code + + # Money * Numeric => Money + assert_kind_of Money, m = (usd * 0.5) + assert_equal 6172, m.rep + assert_equal :USD, m.currency.code + + # Money / Numeric => Money + assert_kind_of Money, m = usd / 3 + assert_equal 4115, m.rep + assert_equal :USD, m.currency.code + + # Money / Money => Numeric + assert_kind_of Numeric, m = usd / Money.new("41.15", :USD) + assert_equal_float 3.0, m + + assert_kind_of Numeric, m = (usd / cad) + assert_equal_float Exchange::Rate::Source::Test.USD_CAD, m, 0.0001 + end + + + def test_pivot_conversions + # Using default get_rate + assert_not_nil cad = Money.new(123.45, :CAD) + assert_not_nil eur = cad.convert(:EUR) + assert_kind_of Numeric, m = (eur.to_f / cad.to_f) + m_expected = (1.0 / Exchange::Rate::Source::Test.USD_CAD) * Exchange::Rate::Source::Test.USD_EUR + # $stderr.puts "m = #{m}, expected = #{m_expected}" + assert_equal_float m_expected, m, 0.001 + + + assert_not_nil gbp = Money.new(123.45, :GBP) + assert_not_nil eur = gbp.convert(:EUR) + assert_kind_of Numeric, m = (eur.to_f / gbp.to_f) + m_expected = (1.0 / Exchange::Rate::Source::Test.USD_GBP) * Exchange::Rate::Source::Test.USD_EUR + # $stderr.puts "m = #{m}, expected = #{m_expected}" + assert_equal_float m_expected, m, 0.001 + end + + + def test_invalid_currency_code + assert_raise Exception::InvalidCurrencyCode do + Money.new(123, :asdf) + end + assert_raise Exception::InvalidCurrencyCode do + Money.new(123, 5) + end + end + + + def test_time_default + Money.default_time = nil + + assert_not_nil usd = Money.new(123.45, :USD) + assert_nil usd.time + + Money.default_time = Time.now + assert_not_nil usd = Money.new(123.45, :USD) + assert_equal usd.time, Money.default_time + end + + + def test_time_now + # Test + Money.default_time = :now + + assert_not_nil usd = Money.new(123.45, :USD) + assert_not_nil usd.time + + sleep 1 + + assert_not_nil usd2 = Money.new(123.45, :USD) + assert_not_nil usd2.time + assert usd.time != usd2.time + + Money.default_time = nil + end + + + def test_time_fixed + # Test for fixed time. + Money.default_time = Time.new + + assert_not_nil usd = Money.new(123.45, :USD) + assert_not_nil usd.time + + sleep 1 + + assert_not_nil usd2 = Money.new(123.45, :USD) + assert_not_nil usd2.time + assert usd.time == usd2.time + end + +end # class + +end # module + diff --git a/test/new_york_fed_test.rb b/test/new_york_fed_test.rb new file mode 100644 index 0000000..569606f --- /dev/null +++ b/test/new_york_fed_test.rb @@ -0,0 +1,73 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/test_base' + +require 'currency' # For :type => :money +require 'currency/exchange/rate/source/new_york_fed' + +module Currency + +class NewYorkFedTest < TestBase + def setup + super + end + + + @@available = nil + + # New York Fed rates are not available on Saturday and Sunday. + def available? + if @@available == nil + @@available = @source.available? + STDERR.puts "Warning: NewYorkFed unavailable on Saturday and Sunday, skipping tests." + end + @@available + end + + + def get_rate_source + # Force NewYorkFed Exchange. + verbose = false + source = @source = Exchange::Rate::Source::NewYorkFed.new(:verbose => verbose) + deriver = Exchange::Rate::Deriver.new(:source => source, :verbose => source.verbose) + end + + + + def test_usd_cad + return unless available? + + assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates + assert_not_nil rates[:USD] + assert_not_nil usd_cad = rates[:USD][:CAD] + + assert_not_nil usd = Money.new(123.45, :USD) + assert_not_nil cad = usd.convert(:CAD) + + assert_kind_of Numeric, m = (cad.to_f / usd.to_f) + # $stderr.puts "m = #{m}" + assert_equal_float usd_cad, m, 0.001 + end + + + def test_cad_eur + return unless available? + + assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates + assert_not_nil rates[:USD] + assert_not_nil usd_cad = rates[:USD][:CAD] + assert_not_nil usd_eur = rates[:USD][:EUR] + + assert_not_nil cad = Money.new(123.45, :CAD) + assert_not_nil eur = cad.convert(:EUR) + + assert_kind_of Numeric, m = (eur.to_f / cad.to_f) + # $stderr.puts "m = #{m}" + assert_equal_float (1.0 / usd_cad) * usd_eur, m, 0.001 + end + +end + +end # module + diff --git a/test/parser_test.rb b/test/parser_test.rb new file mode 100644 index 0000000..7def4bc --- /dev/null +++ b/test/parser_test.rb @@ -0,0 +1,105 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/test_base' +require 'currency' + +module Currency + +class ParserTest < TestBase + def setup + super + @parser = ::Currency::Currency.USD.parser_or_default + end + + ############################################ + # Simple stuff. + # + + def test_default + + end + + + def test_thousands + assert_equal 123456789, @parser.parse("1234567.89").rep + assert_equal 123456789, @parser.parse("1,234,567.89").rep + end + + + def test_cents + assert_equal 123456789, @parser.parse("1234567.89").rep + assert_equal 123456700, @parser.parse("1234567").rep + assert_equal 123456700, @parser.parse("1234567.").rep + assert_equal 123456780, @parser.parse("1234567.8").rep + assert_equal 123456789, @parser.parse("1234567.891").rep + assert_equal -123456700, @parser.parse("-1234567").rep + assert_equal 123456700, @parser.parse("+1234567").rep + end + + + def test_misc + assert_not_nil m = "123.45 USD".money + "100 CAD" + assert ! (m.rep == 200.45) + end + + + def test_round_trip + ::Currency::Currency.default = :USD + assert_not_nil m = ::Currency::Money("1234567.89", :CAD) + assert_not_nil m2 = ::Currency::Money(m.inspect) + assert_equal m.rep, m2.rep + assert_equal m.currency, m2.currency + assert_nil m2.time + assert_equal m.inspect, m2.inspect + end + + + def test_round_trip_time + ::Currency::Currency.default = :USD + time = Time.now.getutc + assert_not_nil m = ::Currency::Money("1234567.89", :CAD, time) + assert_not_nil m.time + assert_not_nil m2 = ::Currency::Money(m.inspect) + assert_not_nil m2.time + assert_equal m.rep, m2.rep + assert_equal m.currency, m2.currency + assert_equal m.time.to_i, m2.time.to_i + assert_equal m.inspect, m2.inspect + end + + + def test_time_nil + parser = ::Currency::Parser.new + parser.time = nil + + assert_not_nil m = parser.parse("$1234.55") + assert_equal nil, m.time + end + + + def test_time + parser = ::Currency::Parser.new + parser.time = Time.new + + assert_not_nil m = parser.parse("$1234.55") + assert_equal parser.time, m.time + end + + + def test_time_now + parser = ::Currency::Parser.new + parser.time = :now + + assert_not_nil m = parser.parse("$1234.55") + assert_not_nil m1_time = m.time + + assert_not_nil m = parser.parse("$1234.55") + assert_not_nil m2_time = m.time + + assert_not_equal m1_time, m2_time + end +end + +end # module + diff --git a/test/test_base.rb b/test/test_base.rb new file mode 100644 index 0000000..3a5b820 --- /dev/null +++ b/test/test_base.rb @@ -0,0 +1,44 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +# Base Test class + +require 'test/unit' +require 'currency' +require 'currency/exchange/rate/source/test' + +module Currency + +class TestBase < Test::Unit::TestCase + def setup + super + @rate_source ||= get_rate_source + Exchange::Rate::Source.default = @rate_source + + # Force non-historical money values. + Money.default_time = nil + end + + + def get_rate_source + source = Exchange::Rate::Source::Test.instance + deriver = Exchange::Rate::Deriver.new(:source => source) + end + + # Avoid "No test were specified" error. + def test_foo + assert true + end + + + # Helpers. + def assert_equal_float(x, y, eps = 1.0e-8) + d = (x * eps).abs + assert((x - d) <= y) + assert(y <= (x + d)) + end + +end # class + +end # module + diff --git a/test/time_quantitizer_test.rb b/test/time_quantitizer_test.rb new file mode 100644 index 0000000..10cc5a5 --- /dev/null +++ b/test/time_quantitizer_test.rb @@ -0,0 +1,136 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +#require File.dirname(__FILE__) + '/../test_helper' + +require 'test/test_base' +require 'currency/exchange/time_quantitizer' + +module Currency +module Exchange + +class TimeQuantitizerTest < TestBase + def setup + super + end + + ############################################ + # + # + + def test_create + assert_kind_of TimeQuantitizer, tq = TimeQuantitizer.new() + assert_equal 60 * 60 * 24, tq.time_quant_size + assert_nil tq.quantitize_time(nil) + + tq + end + + + def test_localtime + t1 = assert_test_day(t0 = Time.new) + assert_equal t0.utc_offset, t1.utc_offset + assert_equal Time.now.utc_offset, t1.utc_offset + end + + + def test_utc + t1 = assert_test_day(t0 = Time.new.utc) + assert_equal t0.utc_offset, t1.utc_offset + end + + + def test_random + (1 .. 1000).each do + t0 = Time.at(rand(1234567901).to_i) + assert_test_day(t0) + assert_test_hour(t0) + # Problem year? + t0 = Time.parse('1977/01/01') + rand(60 * 60 * 24 * 7 * 52).to_i + assert_test_day(t0) + assert_test_hour(t0) + # Problem year? + t0 = Time.parse('1995/01/01') + rand(60 * 60 * 24 * 7 * 52).to_i + assert_test_day(t0) + assert_test_hour(t0) + end + + + end + + + def assert_test_day(t0) + tq = test_create + + begin + assert_not_nil t1 = tq.quantitize_time(t0) + #$stderr.puts "t0 = #{t0}" + #$stderr.puts "t1 = #{t1}" + + assert_equal t0.year, t1.year + assert_equal t0.month, t1.month + assert_equal t0.day, t1.day + assert_time_beginning_of_day(t1) + rescue Object => err + raise("#{err}\nDuring quantitize_time(#{t0} (#{t0.to_i}))") + end + + t1 + end + + + def assert_test_hour(t0) + tq = TimeQuantitizer.new(:time_quant_size => 60 * 60) # 1 hour + + assert_not_nil t1 = tq.quantitize_time(t0) + #$stderr.puts "t0 = #{t0}" + #$stderr.puts "t1 = #{t1}" + + assert_equal t0.year, t1.year + assert_equal t0.month, t1.month + assert_equal t0.day, t1.day + assert_time_beginning_of_hour(t1) + + t1 + end + + + def assert_test_minute(t0) + tq = TimeQuantitizer.new(:time_quant_size => 60) # 1 minute + + tq.local_timezone_offset + + assert_not_nil t1 = tq.quantitize_time(t0) + $stderr.puts "t0 = #{t0}" + $stderr.puts "t1 = #{t1}" + + assert_equal t0.year, t1.year + assert_equal t0.month, t1.month + assert_equal t0.day, t1.day + assert_time_beginning_of_day(t1) + + t1 + end + + + def assert_time_beginning_of_day(t1) + assert_equal 0, t1.hour + assert_time_beginning_of_hour(t1) + end + + + def assert_time_beginning_of_hour(t1) + assert_equal 0, t1.min + assert_time_beginning_of_min(t1) + end + + + def assert_time_beginning_of_min(t1) + assert_equal 0, t1.sec + end + +end # class +end # module +end # module + + diff --git a/test/timed_cache_test.rb b/test/timed_cache_test.rb new file mode 100644 index 0000000..98e3b4c --- /dev/null +++ b/test/timed_cache_test.rb @@ -0,0 +1,95 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/test_base' + +require 'currency' +require 'currency/exchange/rate/source/xe' +require 'currency/exchange/rate/source/timed_cache' + +module Currency + +class TimedCacheTest < TestBase + def setup + super + end + + + def get_rate_source + @source = source = Exchange::Rate::Source::Xe.new + + # source.verbose = true + deriver = Exchange::Rate::Deriver.new(:source => source) + + @cache = cache = Exchange::Rate::Source::TimedCache.new(:source => deriver) + + cache + end + + + def test_timed_cache_usd_cad + assert_not_nil rates = @source.raw_rates + assert_not_nil rates[:USD] + assert_not_nil usd_cad = rates[:USD][:CAD] + + assert_not_nil usd = Money.new(123.45, :USD) + assert_not_nil cad = usd.convert(:CAD) + + assert_kind_of Numeric, m = (cad.to_f / usd.to_f) + # $stderr.puts "m = #{m}" + assert_equal_float usd_cad, m, 0.001 + end + + + def test_timed_cache_cad_eur + assert_not_nil rates = @source.raw_rates + assert_not_nil rates[:USD] + assert_not_nil usd_cad = rates[:USD][:CAD] + assert_not_nil usd_eur = rates[:USD][:EUR] + + assert_not_nil cad = Money.new(123.45, :CAD) + assert_not_nil eur = cad.convert(:EUR) + + assert_kind_of Numeric, m = (eur.to_f / cad.to_f) + # $stderr.puts "m = #{m}" + assert_equal_float((1.0 / usd_cad) * usd_eur, m, 0.001) + end + + + def test_reload + # @cache.verbose = 5 + + test_timed_cache_cad_eur + + assert_not_nil rates = @source.raw_rates + assert_not_nil rates[:USD] + assert_not_nil usd_cad_1 = rates[:USD][:CAD] + + assert_not_nil t1 = @cache.rate_load_time + assert_not_nil t1_reload = @cache.rate_reload_time + assert t1_reload.to_i > t1.to_i + + @cache.time_to_live = 5 + @cache.time_to_live_fudge = 0 + + # puts @cache.rate_reload_time.to_i - @cache.rate_load_time.to_i + assert @cache.rate_reload_time.to_i - @cache.rate_load_time.to_i == @cache.time_to_live + + sleep 10 + + test_timed_cache_cad_eur + + assert_not_nil t2 = @cache.rate_load_time + assert t1.to_i != t2.to_i + + assert_not_nil rates = @source.raw_rates + assert_not_nil rates[:USD] + assert_not_nil usd_cad_2 = rates[:USD][:CAD] + + assert usd_cad_1.object_id != usd_cad_2.object_id + end + +end + +end # module + diff --git a/test/xe_test.rb b/test/xe_test.rb new file mode 100644 index 0000000..ace29d8 --- /dev/null +++ b/test/xe_test.rb @@ -0,0 +1,56 @@ +# Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com> +# See LICENSE.txt for details. + +require 'test/test_base' + +require 'currency' # For :type => :money +require 'currency/exchange/rate/source/xe' + +module Currency + +class XeTest < TestBase + def setup + super + end + + + def get_rate_source + source = Exchange::Rate::Source::Xe.new + # source.verbose = true + deriver = Exchange::Rate::Deriver.new(:source => source) + deriver + end + + + def test_xe_usd_cad + assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates + assert_not_nil rates[:USD] + assert_not_nil usd_cad = rates[:USD][:CAD] + + assert_not_nil usd = Money.new(123.45, :USD) + assert_not_nil cad = usd.convert(:CAD) + + assert_kind_of Numeric, m = (cad.to_f / usd.to_f) + # $stderr.puts "m = #{m}" + assert_equal_float usd_cad, m, 0.001 + end + + + def test_xe_cad_eur + assert_not_nil rates = Exchange::Rate::Source.default.source.raw_rates + assert_not_nil rates[:USD] + assert_not_nil usd_cad = rates[:USD][:CAD] + assert_not_nil usd_eur = rates[:USD][:EUR] + + assert_not_nil cad = Money.new(123.45, :CAD) + assert_not_nil eur = cad.convert(:EUR) + + assert_kind_of Numeric, m = (eur.to_f / cad.to_f) + # $stderr.puts "m = #{m}" + assert_equal_float((1.0 / usd_cad) * usd_eur, m, 0.001) + end + +end + +end # module +
toretore/barby
7d70b456fd679b70dcfe562ff7ea99eda187f390
Remove use of deprecated Minitest::Spec Object methods
diff --git a/barby.gemspec b/barby.gemspec index 0f7ceee..68a0a20 100644 --- a/barby.gemspec +++ b/barby.gemspec @@ -1,31 +1,31 @@ $:.push File.expand_path("../lib", __FILE__) require "barby/version" Gem::Specification.new do |s| s.name = "barby" s.version = Barby::VERSION::STRING s.platform = Gem::Platform::RUBY s.summary = "The Ruby barcode generator" s.email = "[email protected]" s.homepage = "http://toretore.github.com/barby" s.description = "Barby creates barcodes." s.authors = ['Tore Darell'] s.rubyforge_project = "barby" s.extra_rdoc_files = ["README.md"] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.test_files.delete("test/outputter/rmagick_outputter_test.rb") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_development_dependency "minitest", "~> 5.11" - s.add_development_dependency "bundler", "~> 1.16" + s.add_development_dependency "bundler" s.add_development_dependency "rake", "~> 10.0" s.add_development_dependency "rqrcode", "~> 0.10" s.add_development_dependency "prawn", "~> 2.2" s.add_development_dependency "cairo", "~> 1.15" s.add_development_dependency "dmtx", "~> 0.2" end diff --git a/test/bookland_test.rb b/test/bookland_test.rb index e88766a..a797374 100644 --- a/test/bookland_test.rb +++ b/test/bookland_test.rb @@ -1,54 +1,56 @@ require 'test_helper' require 'barby/barcode/bookland' class BooklandTest < Barby::TestCase before do # Gr Publ Tit Checksum @isbn = '96-8261-240-3' @code = Bookland.new(@isbn) end it "should have the expected data" do - @code.data.must_equal '978968261240' + assert_equal '978968261240', @code.data end it "should have the expected numbers" do - @code.numbers.must_equal [9,7,8,9,6,8,2,6,1,2,4,0] + assert_equal [9,7,8,9,6,8,2,6,1,2,4,0], @code.numbers end it "should have the expected checksum" do - @code.checksum.must_equal 4 + assert_equal 4, @code.checksum end it "should raise an error when data not valid" do - lambda{ Bookland.new('1234') }.must_raise ArgumentError + assert_raises ArgumentError do + Bookland.new('1234') + end end describe 'ISBN conversion' do it "should accept ISBN with number system and check digit" do code = Bookland.new('978-82-92526-14-9') assert code.valid? - code.data.must_equal '978829252614' + assert_equal '978829252614', code.data code = Bookland.new('979-82-92526-14-9') assert code.valid? - code.data.must_equal '979829252614' + assert_equal '979829252614', code.data end it "should accept ISBN without number system but with check digit" do code = Bookland.new('82-92526-14-9') assert code.valid? - code.data.must_equal '978829252614' #978 is the default prefix + assert_equal '978829252614', code.data #978 is the default prefix end it "should accept ISBN without number system or check digit" do code = Bookland.new('82-92526-14') assert code.valid? - code.data.must_equal '978829252614' + assert_equal '978829252614', code.data end end end diff --git a/test/codabar_test.rb b/test/codabar_test.rb index 1201dc5..dfa940b 100644 --- a/test/codabar_test.rb +++ b/test/codabar_test.rb @@ -1,58 +1,61 @@ require 'test_helper' require 'barby/barcode/codabar' class CodabarTest < Barby::TestCase describe 'validations' do before do @valid = Codabar.new('A12345D') end it "should be valid with alphabet rounded numbers" do assert @valid.valid? end it "should not be valid with unsupported characters" do @valid.data = "A12345E" refute @valid.valid? end it "should raise an exception when data is invalid" do - lambda{ Codabar.new('A12345E') }.must_raise(ArgumentError) + assert_raises ArgumentError do + Codabar.new('A12345E') + end end end describe 'data' do before do @data = 'A12345D' @code = Codabar.new(@data) end it "should have the same data as was passed to it" do - @code.data.must_equal @data + assert_equal @data, @code.data end end describe 'encoding' do before do @code = Codabar.new('A01D') @code.white_narrow_width = 1 @code.black_narrow_width = 1 @code.wide_width_rate = 2 @code.spacing = 2 end it "should have the expected encoding" do - @code.encoding.must_equal [ + assert_equal [ "1011001001", # A "101010011", # 0 "101011001", # 1 "1010011001", # D - ].join("00") + ].join("00"), + @code.encoding end end end diff --git a/test/code_128_test.rb b/test/code_128_test.rb index 81f60ef..4d62fa1 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,470 +1,476 @@ -# encoding: UTF-8 require 'test_helper' require 'barby/barcode/code_128' class Code128Test < Barby::TestCase %w[CODEA CODEB CODEC FNC1 FNC2 FNC3 FNC4 SHIFT].each do |const| const_set const, Code128.const_get(const) end before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do - @code.send(:stop_encoding).must_equal '1100011101011' + assert_equal '1100011101011', @code.send(:stop_encoding) end it "should find the right class for a character A, B or C" do - @code.send(:class_for, 'A').must_equal Code128A - @code.send(:class_for, 'B').must_equal Code128B - @code.send(:class_for, 'C').must_equal Code128C + assert_equal Code128A, @code.send(:class_for, 'A') + assert_equal Code128B, @code.send(:class_for, 'B') + assert_equal Code128C, @code.send(:class_for, 'C') end it "should find the right change code for a class" do - @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA - @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB - @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC + assert_equal Code128::CODEA, @code.send(:change_code_for_class, Code128A) + assert_equal Code128::CODEB, @code.send(:change_code_for_class, Code128B) + assert_equal Code128::CODEC, @code.send(:change_code_for_class, Code128C) end it "should not allow empty data" do - lambda{ Code128B.new("") }.must_raise(ArgumentError) + assert_raises ArgumentError do + Code128B.new("") + end end describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do - @code.data.must_equal @data + assert_equal @data, @code.data end it "should be able to change its data" do @code.data = '123ABC' - @code.data.must_equal '123ABC' - @code.data.wont_equal @data + assert_equal '123ABC', @code.data + refute_equal @data, @code.data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do - @code.extra_encoding.must_equal '' + assert_equal '', @code.extra_encoding end it "should have the correct checksum" do - @code.checksum.must_equal 66 + assert_equal 66, @code.checksum end it "should return all data for to_s" do - @code.to_s.must_equal @data + assert_equal @data, @code.to_s end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do - @code.full_data.must_equal "ABC123def4567" + assert_equal "ABC123def4567", @code.full_data end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do - @code.full_data_with_change_codes.must_equal @data + assert_equal @data, @code.full_data_with_change_codes end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") - code.full_data.must_equal "ABC1234" - code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") + assert_equal "ABC1234", code.full_data + assert_equal binary_encode("ABC\3071234"), code.full_data_with_change_codes code.extra.extra = binary_encode("\306abc") - code.full_data.must_equal "ABC1234abc" - code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") + assert_equal "ABC1234abc", code.full_data + assert_equal binary_encode("ABC\3071234\306abc"), code.full_data_with_change_codes code.extra.extra.data = binary_encode("abc\305DEF") - code.full_data.must_equal "ABC1234abcDEF" - code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") - code.extra.extra.full_data.must_equal "abcDEF" - code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") - code.extra.full_data.must_equal "1234abcDEF" - code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") + assert_equal "ABC1234abcDEF", code.full_data + assert_equal binary_encode("ABC\3071234\306abc\305DEF"), code.full_data_with_change_codes + assert_equal "abcDEF", code.extra.extra.full_data + assert_equal binary_encode("abc\305DEF"), code.extra.extra.full_data_with_change_codes + assert_equal "1234abcDEF", code.extra.full_data + assert_equal binary_encode("1234\306abc\305DEF"), code.extra.full_data_with_change_codes end it "should have a Code B extra" do - @code.extra.must_be_instance_of(Code128B) + assert @code.extra.is_a?(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do - @code.extra.extra.must_be_instance_of(Code128C) + assert @code.extra.extra.is_a?(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") - @code.data.must_equal '123' - @code.extra.must_be_instance_of(Code128B) - @code.extra.data.must_equal 'abc' + assert_equal '123', @code.data + assert @code.extra.is_a?(Code128B) + assert_equal 'abc', @code.extra.data end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") - @code.extra.must_be_instance_of(Code128C) - @code.extra.data.must_equal '1234' + assert @code.extra.is_a?(Code128C) + assert_equal '1234', @code.extra.data end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") - @code.extra.must_be_instance_of(Code128B) - @code.extra.data.must_equal '123' - @code.extra.extra.must_be_instance_of(Code128C) - @code.extra.extra.data.must_equal '4567' + assert @code.extra.is_a?(Code128B) + assert_equal '123', @code.extra.data + assert @code.extra.extra.is_a?(Code128C) + assert_equal '4567', @code.extra.extra.data end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) - code.data.must_equal "ABC" - code.extra.must_be_instance_of(Code128A) - code.extra.data.must_equal "\n" + assert_equal "ABC", code.data + assert code.extra.is_a?(Code128A) + assert_equal "\n", code.extra.data code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") - code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" + assert_equal "\n\n\n\n\n\nVALID", code.extra.extra.data end it "should raise an exception when extra string doesn't start with the special code character" do - lambda{ @code.extra = '123' }.must_raise ArgumentError + assert_raises ArgumentError do + @code.extra = '123' + end end it "should have the correct checksum" do - @code.checksum.must_equal 84 + assert_equal 84, @code.checksum end it "should have the expected encoding" do - #STARTA A B C 1 2 3 - @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ - #CODEB d e f - '10111101110100001001101011001000010110000100'+ - #CODEC 45 67 - '101110111101011101100010000101100'+ - #CHECK=84 STOP - '100111101001100011101011' + #STARTA A B C 1 2 3 + expected = '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ + #CODEB d e f + '10111101110100001001101011001000010110000100'+ + #CODEC 45 67 + '101110111101011101100010000101100'+ + #CHECK=84 STOP + '100111101001100011101011' + assert_equal expected, @code.encoding end it "should return all data including extras, except change codes for to_s" do - @code.to_s.must_equal "ABC123def4567" + assert_equal "ABC123def4567", @code.to_s end end describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do - @code.characters.must_equal %w(A B C 1 2 3) + assert_equal %w(A B C 1 2 3), @code.characters end it "should have the expected start encoding" do - @code.start_encoding.must_equal '11010000100' + assert_equal '11010000100', @code.start_encoding end it "should have the expected data encoding" do - @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' + assert_equal '101000110001000101100010001000110100111001101100111001011001011100', @code.data_encoding end it "should have the expected encoding" do - @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' + assert_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011', @code.encoding end it "should have the expected checksum encoding" do - @code.checksum_encoding.must_equal '10010000110' + assert_equal '10010000110', @code.checksum_encoding end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do - @code.characters.must_equal %w(a b c 1 2 3) + assert_equal %w(a b c 1 2 3), @code.characters end it "should have the expected start encoding" do - @code.start_encoding.must_equal '11010010000' + assert_equal '11010010000', @code.start_encoding end it "should have the expected data encoding" do - @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' + assert_equal '100101100001001000011010000101100100111001101100111001011001011100', @code.data_encoding end it "should have the expected encoding" do - @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' + assert_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011', @code.encoding end it "should have the expected checksum encoding" do - @code.checksum_encoding.must_equal '11011101110' + assert_equal '11011101110', @code.checksum_encoding end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do - @code.characters.must_equal %w(12 34 56) + assert_equal %w(12 34 56), @code.characters end it "should have the expected start encoding" do - @code.start_encoding.must_equal '11010011100' + assert_equal '11010011100', @code.start_encoding end it "should have the expected data encoding" do - @code.data_encoding.must_equal '101100111001000101100011100010110' + assert_equal '101100111001000101100011100010110', @code.data_encoding end it "should have the expected encoding" do - @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' + assert_equal '11010011100101100111001000101100011100010110100011011101100011101011', @code.encoding end it "should have the expected checksum encoding" do - @code.checksum_encoding.must_equal '10001101110' + assert_equal '10001101110', @code.checksum_encoding end end describe "Function characters" do it "should retain the special symbols in the data accessor" do - Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") - Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") - Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") - Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") + assert_equal binary_encode("\301ABC\301DEF"), Code128A.new(binary_encode("\301ABC\301DEF")).data + assert_equal binary_encode("\301ABC\302DEF"), Code128B.new(binary_encode("\301ABC\302DEF")).data + assert_equal binary_encode("\301123456"), Code128C.new(binary_encode("\301123456")).data + assert_equal binary_encode("12\30134\30156"), Code128C.new(binary_encode("12\30134\30156")).data end it "should keep the special symbols as characters" do - Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) - Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) - Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) - Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) + assert_equal binary_encode_array(%W(\301 A B C \301 D E F)), Code128A.new(binary_encode("\301ABC\301DEF")).characters + assert_equal binary_encode_array(%W(\301 A B C \302 D E F)), Code128B.new(binary_encode("\301ABC\302DEF")).characters + assert_equal binary_encode_array(%W(\301 12 34 56)), Code128C.new(binary_encode("\301123456")).characters + assert_equal binary_encode_array(%W(12 \301 34 \301 56)), Code128C.new(binary_encode("12\30134\30156")).characters end it "should not allow FNC > 1 for Code C" do - lambda{ Code128C.new("12\302") }.must_raise ArgumentError - lambda{ Code128C.new("\30312") }.must_raise ArgumentError - lambda{ Code128C.new("12\304") }.must_raise ArgumentError + assert_raises(ArgumentError){ Code128C.new("12\302") } + assert_raises(ArgumentError){ Code128C.new("\30312") } + assert_raises(ArgumentError){ Code128C.new("12\304") } end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) - a.data_encoding.must_equal '111101011101010001100010001011000' - a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' + assert_equal '111101011101010001100010001011000', a.data_encoding + assert_equal '11010000100111101011101010001100010001011000101000011001100011101011', a.encoding end end describe "Code128 with type" do #it "should raise an exception when not given a type" do # lambda{ Code128.new('abc') }.must_raise(ArgumentError) #end it "should raise an exception when given a non-existent type" do - lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) + assert_raises ArgumentError do + Code128.new('abc', 'F') + end end it "should not fail on frozen type" do Code128.new('123456', 'C'.freeze) # not failing Code128.new('123456', 'c'.freeze) # not failing even when upcasing end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') - code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' + assert_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011', code.encoding end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') - code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' + assert_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011', code.encoding end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') - code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' + assert_equal '11010011100101100111001000101100011100010110100011011101100011101011', code.encoding end end describe "Code128 automatic charset" do =begin 5.4.7.7. Use of Start, Code Set, and Shift Characters to Minimize Symbol Length (Informative) The same data may be represented by different GS1-128 barcodes through the use of different combinations of Start, code set, and shift characters. The following rules should normally be implemented in printer control software to minimise the number of symbol characters needed to represent a given data string (and, therefore, reduce the overall symbol length). * Determine the Start Character: - If the data consists of two digits, use Start Character C. - If the data begins with four or more numeric data characters, use Start Character C. - If an ASCII symbology element (e.g., NUL) occurs in the data before any lowercase character, use Start Character A. - Otherwise, use Start Character B. * If Start Character C is used and the data begins with an odd number of numeric data characters, insert a code set A or code set B character before the last digit, following rules 1c and 1d to determine between code sets A and B. * If four or more numeric data characters occur together when in code sets A or B and: - If there is an even number of numeric data characters, then insert a code set C character before the first numeric digit to change to code set C. - If there is an odd number of numeric data characters, then insert a code set C character immediately after the first numeric digit to change to code set C. * When in code set B and an ASCII symbology element occurs in the data: - If following that character, a lowercase character occurs in the data before the occurrence of another symbology element, then insert a shift character before the symbology element. - Otherwise, insert a code set A character before the symbology element to change to code set A. * When in code set A and a lowercase character occurs in the data: - If following that character, a symbology element occurs in the data before the occurrence of another lowercase character, then insert a shift character before the lowercase character. - Otherwise, insert a code set B character before the lowercase character to change to code set B. When in code set C and a non-numeric character occurs in the data, insert a code set A or code set B character before that character, and follow rules 1c and 1d to determine between code sets A and B. Note: In these rules, the term “lowercase” is used for convenience to mean any code set B character with Code 128 Symbol character values 64 to 95 (ASCII values 96 to 127) (e.g., all lowercase alphanumeric characters plus `{|}~DEL). The term “symbology element” means any code set A character with Code 128 Symbol character values 64 to 95 (ASCII values 00 to 31). Note 2: If the Function 1 Symbol Character (FNC1) occurs in the first position following the Start Character, or in an odd-numbered position in a numeric field, it should be treated as two digits for the purpose of determining the appropriate code set. =end it "should minimize symbol length according to GS1-128 guidelines" do # Determine the Start Character. - Code128.apply_shortest_encoding_for_data("#{FNC1}10").must_equal "#{CODEC}#{FNC1}10" - Code128.apply_shortest_encoding_for_data("#{FNC1}101234").must_equal "#{CODEC}#{FNC1}101234" - Code128.apply_shortest_encoding_for_data("10\001LOT").must_equal "#{CODEA}10\001LOT" - Code128.apply_shortest_encoding_for_data("lot1").must_equal "#{CODEB}lot1" + assert_equal "#{CODEC}#{FNC1}10", Code128.apply_shortest_encoding_for_data("#{FNC1}10") + assert_equal "#{CODEC}#{FNC1}101234", Code128.apply_shortest_encoding_for_data("#{FNC1}101234") + assert_equal "#{CODEA}10\001LOT", Code128.apply_shortest_encoding_for_data("10\001LOT") + assert_equal "#{CODEB}lot1", Code128.apply_shortest_encoding_for_data("lot1") # Switching to codeset B from codeset C - Code128.apply_shortest_encoding_for_data("#{FNC1}101").must_equal "#{CODEC}#{FNC1}10#{CODEB}1" + assert_equal "#{CODEC}#{FNC1}10#{CODEB}1", Code128.apply_shortest_encoding_for_data("#{FNC1}101") # Switching to codeset A from codeset C - Code128.apply_shortest_encoding_for_data("#{FNC1}10\001a").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}a" + assert_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}a", Code128.apply_shortest_encoding_for_data("#{FNC1}10\001a") # Switching to codeset C from codeset A - Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT#{CODEC}1234" - Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT1#{CODEC}2345" + assert_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT#{CODEC}1234", Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT1234") + assert_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT1#{CODEC}2345", Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT12345") # Switching to codeset C from codeset B - Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}1234" - Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT1#{CODEC}2345" + assert_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}1234", Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT1234") + assert_equal "#{CODEC}#{FNC1}10#{CODEB}LOT1#{CODEC}2345", Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT12345") # Switching to codeset A from codeset B - Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001a").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{SHIFT}\001a" - Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001\001").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{CODEA}\001\001" + assert_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{SHIFT}\001a", Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001a") + assert_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{CODEA}\001\001", Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001\001") # Switching to codeset B from codeset A - Code128.apply_shortest_encoding_for_data("#{FNC1}10\001l\001").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{SHIFT}l\001" - Code128.apply_shortest_encoding_for_data("#{FNC1}10\001ll").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}ll" + assert_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{SHIFT}l\001", Code128.apply_shortest_encoding_for_data("#{FNC1}10\001l\001") + assert_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}ll", Code128.apply_shortest_encoding_for_data("#{FNC1}10\001ll") # testing "Note 2" from the GS1 specification - Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}0101").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}#{FNC1}0101" - Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}01010").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{FNC1}0#{CODEC}1010" - Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT01#{FNC1}0101").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}01#{FNC1}0101" + assert_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}#{FNC1}0101", Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}0101") + assert_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{FNC1}0#{CODEC}1010", Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}01010") + assert_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}01#{FNC1}0101", Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT01#{FNC1}0101") end it "should know how to extract CODEC segments properly from a data string" do - Code128.send(:extract_codec, "1234abcd5678\r\n\r\n").must_equal ["1234", "abcd", "5678", "\r\n\r\n"] - Code128.send(:extract_codec, "12345abc6").must_equal ["1234", "5abc6"] - Code128.send(:extract_codec, "abcdef").must_equal ["abcdef"] - Code128.send(:extract_codec, "123abcdef45678").must_equal ["123abcdef4", "5678"] - Code128.send(:extract_codec, "abcd12345").must_equal ["abcd1", "2345"] - Code128.send(:extract_codec, "abcd12345efg").must_equal ["abcd1", "2345", "efg"] - Code128.send(:extract_codec, "12345").must_equal ["1234", "5"] - Code128.send(:extract_codec, "12345abc").must_equal ["1234", "5abc"] - Code128.send(:extract_codec, "abcdef1234567").must_equal ["abcdef1", "234567"] + assert_equal ["1234", "abcd", "5678", "\r\n\r\n"], Code128.send(:extract_codec, "1234abcd5678\r\n\r\n") + assert_equal ["1234", "5abc6"], Code128.send(:extract_codec, "12345abc6") + assert_equal ["abcdef"], Code128.send(:extract_codec, "abcdef") + assert_equal ["123abcdef4", "5678"], Code128.send(:extract_codec, "123abcdef45678") + assert_equal ["abcd1", "2345"], Code128.send(:extract_codec, "abcd12345") + assert_equal ["abcd1", "2345", "efg"], Code128.send(:extract_codec, "abcd12345efg") + assert_equal ["1234", "5"], Code128.send(:extract_codec, "12345") + assert_equal ["1234", "5abc"], Code128.send(:extract_codec, "12345abc") + assert_equal ["abcdef1", "234567"], Code128.send(:extract_codec, "abcdef1234567") end it "should know how to most efficiently apply different encodings to a data string" do - Code128.apply_shortest_encoding_for_data("123456").must_equal "#{CODEC}123456" - Code128.apply_shortest_encoding_for_data("abcdef").must_equal "#{CODEB}abcdef" - Code128.apply_shortest_encoding_for_data("ABCDEF").must_equal "#{CODEB}ABCDEF" - Code128.apply_shortest_encoding_for_data("\n\t\r").must_equal "#{CODEA}\n\t\r" - Code128.apply_shortest_encoding_for_data("123456abcdef").must_equal "#{CODEC}123456#{CODEB}abcdef" - Code128.apply_shortest_encoding_for_data("abcdef123456").must_equal "#{CODEB}abcdef#{CODEC}123456" - Code128.apply_shortest_encoding_for_data("1234567").must_equal "#{CODEC}123456#{CODEB}7" - Code128.apply_shortest_encoding_for_data("123b456").must_equal "#{CODEB}123b456" - Code128.apply_shortest_encoding_for_data("abc123def45678gh").must_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh" - Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n").must_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n" - Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567").must_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" - - Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl" - Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456").must_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456" - Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs" + assert_equal "#{CODEC}123456", Code128.apply_shortest_encoding_for_data("123456") + assert_equal "#{CODEB}abcdef", Code128.apply_shortest_encoding_for_data("abcdef") + assert_equal "#{CODEB}ABCDEF", Code128.apply_shortest_encoding_for_data("ABCDEF") + assert_equal "#{CODEA}\n\t\r", Code128.apply_shortest_encoding_for_data("\n\t\r") + assert_equal "#{CODEC}123456#{CODEB}abcdef", Code128.apply_shortest_encoding_for_data("123456abcdef") + assert_equal "#{CODEB}abcdef#{CODEC}123456", Code128.apply_shortest_encoding_for_data("abcdef123456") + assert_equal "#{CODEC}123456#{CODEB}7", Code128.apply_shortest_encoding_for_data("1234567") + assert_equal "#{CODEB}123b456", Code128.apply_shortest_encoding_for_data("123b456") + assert_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh", Code128.apply_shortest_encoding_for_data("abc123def45678gh") + assert_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n", Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n") + assert_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567", Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567") + + assert_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl", Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl") + assert_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456", Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456") + assert_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs", Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs") end it "should apply automatic charset when no charset is given" do b = Code128.new("123456QWERTY\r\n\tAAbbcc12XX34567") - b.type.must_equal 'C' - b.full_data_with_change_codes.must_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" + assert_equal 'C', b.type + assert_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567", b.full_data_with_change_codes end end private def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end end diff --git a/test/code_25_iata_test.rb b/test/code_25_iata_test.rb index 14715cb..f04b6db 100644 --- a/test/code_25_iata_test.rb +++ b/test/code_25_iata_test.rb @@ -1,19 +1,19 @@ require 'test_helper' require 'barby/barcode/code_25_iata' class Code25IATATest < Barby::TestCase before do @data = '0123456789' @code = Code25IATA.new(@data) end it "should have the expected start_encoding" do - @code.start_encoding.must_equal '1010' + assert_equal '1010', @code.start_encoding end it "should have the expected stop_encoding" do - @code.stop_encoding.must_equal '11101' + assert_equal '11101', @code.stop_encoding end end diff --git a/test/code_25_interleaved_test.rb b/test/code_25_interleaved_test.rb index f9bc5e6..f006e63 100644 --- a/test/code_25_interleaved_test.rb +++ b/test/code_25_interleaved_test.rb @@ -1,116 +1,122 @@ require 'test_helper' require 'barby/barcode/code_25_interleaved' class Code25InterleavedTest < Barby::TestCase before do @data = '12345670' @code = Code25Interleaved.new(@data) end it "should have the expected digit_pairs" do - @code.digit_pairs.must_equal [[1,2],[3,4],[5,6],[7,0]] + assert_equal [[1,2],[3,4],[5,6],[7,0]], @code.digit_pairs end it "should have the expected digit_encodings" do - @code.digit_encodings.must_equal %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110) + assert_equal %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110), @code.digit_encodings end it "should have the expected start_encoding" do - @code.start_encoding.must_equal '1010' + assert_equal '1010', @code.start_encoding end it "should have the expected stop_encoding" do - @code.stop_encoding.must_equal '11101' + assert_equal '11101', @code.stop_encoding end it "should have the expected data_encoding" do - @code.data_encoding.must_equal "111010001010111000111011101000101000111010001110001010101010001110001110" + assert_equal "111010001010111000111011101000101000111010001110001010101010001110001110", @code.data_encoding end it "should have the expected encoding" do - @code.encoding.must_equal "101011101000101011100011101110100010100011101000111000101010101000111000111011101" + assert_equal "101011101000101011100011101110100010100011101000111000101010101000111000111011101", @code.encoding end it "should be valid" do assert @code.valid? end it "should return the expected encoding for parameters passed to encoding_for_interleaved" do w, n = Code25Interleaved::WIDE, Code25Interleaved::NARROW # 1 2 1 2 1 2 1 2 1 2 digits 1 and 2 # B S B S B S B S B S bars and spaces - @code.encoding_for_interleaved(w,n,n,w,n,n,n,n,w,w).must_equal '111010001010111000' + assert_equal '111010001010111000', @code.encoding_for_interleaved(w,n,n,w,n,n,n,n,w,w) # 3 4 3 4 3 4 3 4 3 4 digits 3 and 4 # B S B S B S B S B S bars and spaces - @code.encoding_for_interleaved(w,n,w,n,n,w,n,n,n,w).must_equal '111011101000101000' + assert_equal '111011101000101000', @code.encoding_for_interleaved(w,n,w,n,n,w,n,n,n,w) end it "should return all characters in sequence for to_s" do - @code.to_s.must_equal @code.characters.join + assert_equal @code.characters.join, @code.to_s end - + describe "with checksum" do before do @data = '1234567' @code = Code25Interleaved.new(@data) @code.include_checksum = true end it "should have the expected digit_pairs_with_checksum" do - @code.digit_pairs_with_checksum.must_equal [[1,2],[3,4],[5,6],[7,0]] + assert_equal [[1,2],[3,4],[5,6],[7,0]], @code.digit_pairs_with_checksum end it "should have the expected digit_encodings_with_checksum" do - @code.digit_encodings_with_checksum.must_equal %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110) + assert_equal %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110), @code.digit_encodings_with_checksum end it "should have the expected data_encoding_with_checksum" do - @code.data_encoding_with_checksum.must_equal "111010001010111000111011101000101000111010001110001010101010001110001110" + assert_equal "111010001010111000111011101000101000111010001110001010101010001110001110", @code.data_encoding_with_checksum end it "should have the expected encoding" do - @code.encoding.must_equal "101011101000101011100011101110100010100011101000111000101010101000111000111011101" + assert_equal "101011101000101011100011101110100010100011101000111000101010101000111000111011101", @code.encoding end it "should be valid" do assert @code.valid? end it "should return all characters including checksum in sequence on to_s" do - @code.to_s.must_equal @code.characters_with_checksum.join + assert_equal @code.characters_with_checksum.join, @code.to_s end end describe "with invalid number of digits" do before do @data = '1234567' @code = Code25Interleaved.new(@data) end it "should not be valid" do refute @code.valid? end it "should raise ArgumentError on all encoding methods" do - lambda{ @code.encoding }.must_raise(ArgumentError) - lambda{ @code.data_encoding }.must_raise(ArgumentError) - lambda{ @code.digit_encodings }.must_raise(ArgumentError) + assert_raises ArgumentError do + @code.encoding + end + assert_raises ArgumentError do + @code.data_encoding + end + assert_raises ArgumentError do + @code.digit_encodings + end end it "should not raise ArgumentError on encoding methods that include checksum" do b = Code25Interleaved.new(@data) b.include_checksum = true b.encoding @code.data_encoding_with_checksum @code.digit_encodings_with_checksum end end end diff --git a/test/code_25_test.rb b/test/code_25_test.rb index 2264bfe..8409b85 100644 --- a/test/code_25_test.rb +++ b/test/code_25_test.rb @@ -1,110 +1,120 @@ require 'test_helper' require 'barby/barcode/code_25' class Code25Test < Barby::TestCase before do @data = "1234567" @code = Code25.new(@data) end it "should return the same data it was given" do - @code.data.must_equal @data + assert_equal @data, @code.data end it "should have the expected characters" do - @code.characters.must_equal %w(1 2 3 4 5 6 7) + assert_equal %w(1 2 3 4 5 6 7), @code.characters end it "should have the expected characters_with_checksum" do - @code.characters_with_checksum.must_equal %w(1 2 3 4 5 6 7 0) + assert_equal %w(1 2 3 4 5 6 7 0), @code.characters_with_checksum end it "should have the expected digits" do - @code.digits.must_equal [1,2,3,4,5,6,7] + assert_equal [1,2,3,4,5,6,7], @code.digits end it "should have the expected digits_with_checksum" do - @code.digits_with_checksum.must_equal [1,2,3,4,5,6,7,0] + assert_equal [1,2,3,4,5,6,7,0], @code.digits_with_checksum end it "should have the expected even_and_odd_digits" do - @code.even_and_odd_digits.must_equal [[7,5,3,1], [6,4,2]] + assert_equal [[7,5,3,1], [6,4,2]], @code.even_and_odd_digits end it "should have the expected start_encoding" do - @code.start_encoding.must_equal '1110111010' + assert_equal '1110111010', @code.start_encoding end it "should have the expected stop_encoding" do - @code.stop_encoding.must_equal '111010111' + assert_equal '111010111', @code.stop_encoding end it "should have a default narrow_width of 1" do - @code.narrow_width.must_equal 1 + assert_equal 1, @code.narrow_width end it "should have a default wide_width equal to narrow_width * 3" do - @code.wide_width.must_equal @code.narrow_width * 3 + assert_equal @code.narrow_width * 3, @code.wide_width @code.narrow_width = 2 - @code.wide_width.must_equal 6 + assert_equal 6, @code.wide_width end it "should have a default space_width equal to narrow_width" do - @code.space_width.must_equal @code.narrow_width + assert_equal @code.narrow_width, @code.space_width @code.narrow_width = 23 - @code.space_width.must_equal 23 + assert_equal 23, @code.space_width end it "should have the expected digit_encodings" do - @code.digit_encodings.must_equal %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110) + assert_equal %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110), @code.digit_encodings end it "should have the expected digit_encodings_with_checksum" do - @code.digit_encodings_with_checksum.must_equal %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110 10101110111010) + assert_equal %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110 10101110111010), @code.digit_encodings_with_checksum end it "should have the expected data_encoding" do - @code.data_encoding.must_equal "11101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110" + assert_equal "11101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110", @code.data_encoding end it "should have the expected checksum" do - @code.checksum.must_equal 0 + assert_equal 0, @code.checksum end it "should have the expected checksum_encoding" do - @code.checksum_encoding.must_equal '10101110111010' + assert_equal '10101110111010', @code.checksum_encoding end it "should have the expected encoding" do - @code.encoding.must_equal "111011101011101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110111010111" + assert_equal "111011101011101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110111010111", @code.encoding end it "should be valid" do assert @code.valid? end it "should not be valid" do @code.data = 'abc' refute @code.valid? end it "should raise on encoding methods that include data encoding if not valid" do @code.data = 'abc' - lambda{ @code.encoding }.must_raise ArgumentError - lambda{ @code.data_encoding }.must_raise ArgumentError - lambda{ @code.data_encoding_with_checksum }.must_raise ArgumentError - lambda{ @code.digit_encodings }.must_raise ArgumentError - lambda{ @code.digit_encodings_with_checksum }.must_raise ArgumentError + assert_raises ArgumentError do + @code.encoding + end + assert_raises ArgumentError do + @code.data_encoding + end + assert_raises ArgumentError do + @code.data_encoding_with_checksum + end + assert_raises ArgumentError do + @code.digit_encodings + end + assert_raises ArgumentError do + @code.digit_encodings_with_checksum + end end it "should return all characters in sequence on to_s" do - @code.to_s.must_equal @code.characters.join + assert_equal @code.characters.join, @code.to_s end it "should include checksum in to_s when include_checksum is true" do @code.include_checksum = true - @code.to_s.must_equal @code.characters_with_checksum.join + assert_equal @code.characters_with_checksum.join, @code.to_s end end diff --git a/test/code_39_test.rb b/test/code_39_test.rb index 7d60de9..0de429b 100644 --- a/test/code_39_test.rb +++ b/test/code_39_test.rb @@ -1,210 +1,213 @@ #encoding: ASCII require 'test_helper' require 'barby/barcode/code_39' class Code39Test < Barby::TestCase before do @data = 'TEST8052' @code = Code39.new(@data) @code.spacing = 3 end it "should yield self on initialize" do c1 = nil c2 = Code39.new('TEST'){|c| c1 = c } - c1.must_equal c2 + assert_equal c2, c1 end it "should have the expected data" do - @code.data.must_equal @data + assert_equal @data, @code.data end it "should have the expected characters" do - @code.characters.must_equal @data.split(//) + assert_equal @data.split(//), @code.characters end it "should have the expected start_encoding" do - @code.start_encoding.must_equal '100101101101' + assert_equal '100101101101', @code.start_encoding end it "should have the expected stop_encoding" do - @code.stop_encoding.must_equal '100101101101' + assert_equal '100101101101', @code.stop_encoding end it "should have the expected spacing_encoding" do - @code.spacing_encoding.must_equal '000' + assert_equal '000', @code.spacing_encoding end it "should have the expected encoded characters" do - @code.encoded_characters.must_equal %w(101011011001 110101100101 101101011001 101011011001 110100101101 101001101101 110100110101 101100101011) + assert_equal %w(101011011001 110101100101 101101011001 101011011001 110100101101 101001101101 110100110101 101100101011), @code.encoded_characters end it "should have the expected data_encoding" do - @code.data_encoding.must_equal '101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011' + assert_equal '101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011', @code.data_encoding end it "should have the expected encoding" do - @code.encoding.must_equal '100101101101000101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011000100101101101' + assert_equal '100101101101000101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011000100101101101', @code.encoding end it "should be valid" do assert @code.valid? end it "should not be valid" do @code.data = "123\200456" refute @code.valid? end it "should raise an exception when data is not valid on initialization" do - lambda{ Code39.new('abc') }.must_raise(ArgumentError) + assert_raises ArgumentError do + Code39.new('abc') + end end it "should return all characters in sequence without checksum on to_s" do - @code.to_s.must_equal @data + assert_equal @data, @code.to_s end - + describe "Checksumming" do before do @code = Code39.new('CODE39') end it "should have the expected checksum" do - @code.checksum.must_equal 32 + assert_equal 32, @code.checksum end it "should have the expected checksum_character" do - @code.checksum_character.must_equal 'W' + assert_equal 'W', @code.checksum_character end it "should have the expected checksum_encoding" do - @code.checksum_encoding.must_equal '110011010101' + assert_equal '110011010101', @code.checksum_encoding end it "should have the expected characters_with_checksum" do - @code.characters_with_checksum.must_equal %w(C O D E 3 9 W) + assert_equal %w(C O D E 3 9 W), @code.characters_with_checksum end it "should have the expected encoded_characters_with_checksum" do - @code.encoded_characters_with_checksum.must_equal %w(110110100101 110101101001 101011001011 110101100101 110110010101 101100101101 110011010101) + assert_equal %w(110110100101 110101101001 101011001011 110101100101 110110010101 101100101101 110011010101), @code.encoded_characters_with_checksum end it "should have the expected data_encoding_with_checksum" do - @code.data_encoding_with_checksum.must_equal "110110100101011010110100101010110010110110101100101011011001010101011001011010110011010101" + assert_equal "110110100101011010110100101010110010110110101100101011011001010101011001011010110011010101", @code.data_encoding_with_checksum end it "should have the expected encoding_with_checksum" do - @code.encoding_with_checksum.must_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" + assert_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101", @code.encoding_with_checksum end it "should return the encoding with checksum when include_checksum == true" do @code.include_checksum = true - @code.encoding.must_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" + assert_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101", @code.encoding end end describe "Normal encoding" do before do @data = 'ABC$%' @code = Code39.new(@data) end it "should have the expected characters" do - @code.characters.must_equal %w(A B C $ %) + assert_equal %w(A B C $ %), @code.characters end it "should have the expected encoded_characters" do - @code.encoded_characters.must_equal %w(110101001011 101101001011 110110100101 100100100101 101001001001) + assert_equal %w(110101001011 101101001011 110110100101 100100100101 101001001001), @code.encoded_characters end it "should have the expected data_encoding" do - @code.data_encoding.must_equal '1101010010110101101001011011011010010101001001001010101001001001' + assert_equal '1101010010110101101001011011011010010101001001001010101001001001', @code.data_encoding end it "should not be valid" do @code.data = 'abc' refute @code.valid? end end describe "Extended encoding" do before do @data = '<abc>' @code = Code39.new(@data, true) end it "should return true on extended?" do assert @code.extended? end it "should have the expected characters" do - @code.characters.must_equal %w(% G + A + B + C % I) + assert_equal %w(% G + A + B + C % I), @code.characters end it "should have the expected encoded_characters" do - @code.encoded_characters.must_equal %w(101001001001 101010011011 100101001001 110101001011 100101001001 101101001011 100101001001 110110100101 101001001001 101101001101) + assert_equal %w(101001001001 101010011011 100101001001 110101001011 100101001001 101101001011 100101001001 110110100101 101001001001 101101001101), @code.encoded_characters end it "should have the expected data_encoding" do - @code.data_encoding.must_equal '101001001001010101001101101001010010010110101001011010010100100101011010010110100101001001011011010010101010010010010101101001101' + assert_equal '101001001001010101001101101001010010010110101001011010010100100101011010010110100101001001011011010010101010010010010101101001101', @code.data_encoding end it "should have the expected encoding" do - @code.encoding.must_equal '10010110110101010010010010101010011011010010100100101101010010110100101001001'+ - '010110100101101001010010010110110100101010100100100101011010011010100101101101' + assert_equal '10010110110101010010010010101010011011010010100100101101010010110100101001001'+ + '010110100101101001010010010110110100101010100100100101011010011010100101101101', + @code.encoding end it "should take a second parameter on initialize indicating it is extended" do assert Code39.new('abc', true).extended? refute Code39.new('ABC', false).extended? refute Code39.new('ABC').extended? end it "should be valid" do assert @code.valid? end it "should not be valid" do @code.data = "abc\200123" refute @code.valid? end it "should return all characters in sequence without checksum on to_s" do - @code.to_s.must_equal @data + assert_equal @data, @code.to_s end end describe "Variable widths" do before do @data = 'ABC$%' @code = Code39.new(@data) @code.narrow_width = 2 @code.wide_width = 5 end it "should have the expected encoded_characters" do - @code.encoded_characters.must_equal %w(111110011001100000110011111 110011111001100000110011111 111110011111001100000110011 110000011000001100000110011 110011000001100000110000011) + assert_equal %w(111110011001100000110011111 110011111001100000110011111 111110011111001100000110011 110000011000001100000110011 110011000001100000110000011), @code.encoded_characters end it "should have the expected data_encoding" do # A SB SC S$ S% - @code.data_encoding.must_equal '1111100110011000001100111110110011111001100000110011111011111001111100110000011001101100000110000011000001100110110011000001100000110000011' + assert_equal '1111100110011000001100111110110011111001100000110011111011111001111100110000011001101100000110000011000001100110110011000001100000110000011', @code.data_encoding @code.spacing = 3 # A S B S C S $ S % - @code.data_encoding.must_equal '111110011001100000110011111000110011111001100000110011111000111110011111001100000110011000110000011000001100000110011000110011000001100000110000011' + assert_equal '111110011001100000110011111000110011111001100000110011111000111110011111001100000110011000110000011000001100000110011000110011000001100000110000011', @code.data_encoding end end end diff --git a/test/code_93_test.rb b/test/code_93_test.rb index 5a9615b..d535e1f 100644 --- a/test/code_93_test.rb +++ b/test/code_93_test.rb @@ -1,144 +1,147 @@ #encoding: ASCII require 'test_helper' require 'barby/barcode/code_93' class Code93Test < Barby::TestCase before do @data = 'TEST93' @code = Code93.new(@data) end it "should return the same data we put in" do - @code.data.must_equal @data + assert_equal @data, @code.data end it "should have the expected characters" do - @code.characters.must_equal @data.split(//) + assert_equal @data.split(//), @code.characters end it "should have the expected start_encoding" do - @code.start_encoding.must_equal '101011110' + assert_equal '101011110', @code.start_encoding end it "should have the expected stop_encoding" do # STOP TERM - @code.stop_encoding.must_equal '1010111101' + assert_equal '1010111101', @code.stop_encoding end it "should have the expected encoded characters" do # T E S T 9 3 - @code.encoded_characters.must_equal %w(110100110 110010010 110101100 110100110 100001010 101000010) + assert_equal %w(110100110 110010010 110101100 110100110 100001010 101000010), @code.encoded_characters end it "should have the expected data_encoding" do # T E S T 9 3 - @code.data_encoding.must_equal "110100110110010010110101100110100110100001010101000010" + assert_equal "110100110110010010110101100110100110100001010101000010", @code.data_encoding end it "should have the expected data_encoding_with_checksums" do # T E S T 9 3 + (C) 6 (K) - @code.data_encoding_with_checksums.must_equal "110100110110010010110101100110100110100001010101000010101110110100100010" + assert_equal "110100110110010010110101100110100110100001010101000010101110110100100010", @code.data_encoding_with_checksums end it "should have the expected encoding" do # START T E S T 9 3 + (C) 6 (K) STOP TERM - @code.encoding.must_equal "1010111101101001101100100101101011001101001101000010101010000101011101101001000101010111101" + assert_equal "1010111101101001101100100101101011001101001101000010101010000101011101101001000101010111101", @code.encoding end it "should have the expected checksum_values" do - @code.checksum_values.must_equal [29, 14, 28, 29, 9, 3].reverse #! + assert_equal [29, 14, 28, 29, 9, 3].reverse, @code.checksum_values #! end it "should have the expected c_checksum" do - @code.c_checksum.must_equal 41 #calculate this first! + assert_equal 41, #calculate this first! + @code.c_checksum end it "should have the expected c_checksum_character" do - @code.c_checksum_character.must_equal '+' + assert_equal '+', @code.c_checksum_character end it "should have the expected c_checksum_encoding" do - @code.c_checksum_encoding.must_equal '101110110' + assert_equal '101110110', @code.c_checksum_encoding end it "should have the expected checksum_values_with_c_checksum" do - @code.checksum_values_with_c_checksum.must_equal [29, 14, 28, 29, 9, 3, 41].reverse #! + assert_equal [29, 14, 28, 29, 9, 3, 41].reverse, @code.checksum_values_with_c_checksum #! end it "should have the expected k_checksum" do - @code.k_checksum.must_equal 6 #calculate this first! + assert_equal 6, #calculate this first! + @code.k_checksum end it "should have the expected k_checksum_character" do - @code.k_checksum_character.must_equal '6' + assert_equal '6', @code.k_checksum_character end it "should have the expected k_checksum_encoding" do - @code.k_checksum_encoding.must_equal '100100010' + assert_equal '100100010', @code.k_checksum_encoding end it "should have the expected checksums" do - @code.checksums.must_equal [41, 6] + assert_equal [41, 6], @code.checksums end it "should have the expected checksum_characters" do - @code.checksum_characters.must_equal ['+', '6'] + assert_equal ['+', '6'], @code.checksum_characters end it "should have the expected checksum_encodings" do - @code.checksum_encodings.must_equal %w(101110110 100100010) + assert_equal %w(101110110 100100010), @code.checksum_encodings end it "should have the expected checksum_encoding" do - @code.checksum_encoding.must_equal '101110110100100010' + assert_equal '101110110100100010', @code.checksum_encoding end it "should be valid" do assert @code.valid? end it "should not be valid when not in extended mode" do @code.data = 'not extended' end it "should return data with no checksums on to_s" do - @code.to_s.must_equal 'TEST93' + assert_equal 'TEST93', @code.to_s end - + describe "Extended mode" do before do @data = "Extended!" @code = Code93.new(@data) end it "should be extended" do assert @code.extended? end it "should convert extended characters to special shift characters" do - @code.characters.must_equal ["E", "\304", "X", "\304", "T", "\304", "E", "\304", "N", "\304", "D", "\304", "E", "\304", "D", "\303", "A"] + assert_equal ["E", "\304", "X", "\304", "T", "\304", "E", "\304", "N", "\304", "D", "\304", "E", "\304", "D", "\303", "A"], @code.characters end it "should have the expected data_encoding" do - @code.data_encoding.must_equal '110010010100110010101100110100110010110100110100110010110010010'+ - '100110010101000110100110010110010100100110010110010010100110010110010100111010110110101000' + assert_equal '110010010100110010101100110100110010110100110100110010110010010'+ + '100110010101000110100110010110010100100110010110010010100110010110010100111010110110101000', + @code.data_encoding end it "should have the expected c_checksum" do - @code.c_checksum.must_equal 9 + assert_equal 9, @code.c_checksum end it "should have the expected k_checksum" do - @code.k_checksum.must_equal 46 + assert_equal 46, @code.k_checksum end it "should return the original data on to_s with no checksums" do - @code.to_s.must_equal 'Extended!' + assert_equal 'Extended!', @code.to_s end end end diff --git a/test/data_matrix_test.rb b/test/data_matrix_test.rb index aa5a37d..b03476f 100644 --- a/test/data_matrix_test.rb +++ b/test/data_matrix_test.rb @@ -1,40 +1,41 @@ require 'test_helper' require 'barby/barcode/data_matrix' class DataMatrixTest < Barby::TestCase before do @data = "humbaba" @code = Barby::DataMatrix.new(@data) end it "should have the expected encoding" do - @code.encoding.must_equal [ + assert_equal [ "10101010101010", "10111010000001", "11100101101100", "11101001110001", "11010101111110", "11100101100001", "11011001011110", "10011011010011", "11011010000100", "10101100101001", "11011100001100", "10101110110111", "11000001010100", "11111111111111", - ] + ], + @code.encoding end it "should return data on to_s" do - @code.to_s.must_equal @data + assert_equal @data, @code.to_s end it "should be able to change its data" do prev_encoding = @code.encoding @code.data = "after eight" - @code.encoding.wont_equal prev_encoding + refute_equal prev_encoding, @code.encoding end end diff --git a/test/ean13_test.rb b/test/ean13_test.rb index 82222db..11cebe4 100644 --- a/test/ean13_test.rb +++ b/test/ean13_test.rb @@ -1,169 +1,172 @@ require 'test_helper' require 'barby/barcode/ean_13' class EAN13Test < Barby::TestCase describe 'validations' do before do @valid = EAN13.new('123456789012') end it "should be valid with 12 digits" do assert @valid.valid? end it "should not be valid with non-digit characters" do @valid.data = "The shit apple doesn't fall far from the shit tree" refute @valid.valid? end it "should not be valid with less than 12 digits" do @valid.data = "12345678901" refute @valid.valid? end it "should not be valid with more than 12 digits" do @valid.data = "1234567890123" refute @valid.valid? end it "should raise an exception when data is invalid" do - lambda{ EAN13.new('123') }.must_raise(ArgumentError) + assert_raises ArgumentError do + EAN13.new('123') + end end end describe 'data' do before do @data = '007567816412' @code = EAN13.new(@data) end it "should have the same data as was passed to it" do - @code.data.must_equal @data + assert_equal @data, @code.data end it "should have the expected characters" do - @code.characters.must_equal @data.split(//) + assert_equal @data.split(//), @code.characters end it "should have the expected numbers" do - @code.numbers.must_equal @data.split(//).map{|s| s.to_i } + assert_equal @data.split(//).map{|s| s.to_i }, @code.numbers end it "should have the expected odd_and_even_numbers" do - @code.odd_and_even_numbers.must_equal [[2,4,1,7,5,0], [1,6,8,6,7,0]] + assert_equal [[2,4,1,7,5,0], [1,6,8,6,7,0]], @code.odd_and_even_numbers end it "should have the expected left_numbers" do - #0=second number in number system code - @code.left_numbers.must_equal [0,7,5,6,7,8] + # 0=second number in number system code + assert_equal [0,7,5,6,7,8], @code.left_numbers end it "should have the expected right_numbers" do - @code.right_numbers.must_equal [1,6,4,1,2,5]#5=checksum + # 5=checksum + assert_equal [1,6,4,1,2,5], @code.right_numbers end it "should have the expected numbers_with_checksum" do - @code.numbers_with_checksum.must_equal @data.split(//).map{|s| s.to_i } + [5] + assert_equal @data.split(//).map{|s| s.to_i } + [5], @code.numbers_with_checksum end it "should have the expected data_with_checksum" do - @code.data_with_checksum.must_equal @data+'5' + assert_equal @data+'5', @code.data_with_checksum end it "should return all digits and the checksum on to_s" do - @code.to_s.must_equal '0075678164125' + assert_equal '0075678164125', @code.to_s end end describe 'checksum' do before do @code = EAN13.new('007567816412') end it "should have the expected weighted_sum" do - @code.weighted_sum.must_equal 85 + assert_equal 85, @code.weighted_sum @code.data = '007567816413' - @code.weighted_sum.must_equal 88 + assert_equal 88, @code.weighted_sum end it "should have the correct checksum" do - @code.checksum.must_equal 5 + assert_equal 5, @code.checksum @code.data = '007567816413' - @code.checksum.must_equal 2 + assert_equal 2, @code.checksum end it "should have the correct checksum_encoding" do - @code.checksum_encoding.must_equal '1001110' + assert_equal '1001110', @code.checksum_encoding end end describe 'encoding' do before do @code = EAN13.new('750103131130') end it "should have the expected checksum" do - @code.checksum.must_equal 9 + assert_equal 9, @code.checksum end it "should have the expected checksum_encoding" do - @code.checksum_encoding.must_equal '1110100' + assert_equal '1110100', @code.checksum_encoding end it "should have the expected left_parity_map" do - @code.left_parity_map.must_equal [:odd, :even, :odd, :even, :odd, :even] + assert_equal [:odd, :even, :odd, :even, :odd, :even], @code.left_parity_map end it "should have the expected left_encodings" do - @code.left_encodings.must_equal %w(0110001 0100111 0011001 0100111 0111101 0110011) + assert_equal %w(0110001 0100111 0011001 0100111 0111101 0110011), @code.left_encodings end it "should have the expected right_encodings" do - @code.right_encodings.must_equal %w(1000010 1100110 1100110 1000010 1110010 1110100) + assert_equal %w(1000010 1100110 1100110 1000010 1110010 1110100), @code.right_encodings end it "should have the expected left_encoding" do - @code.left_encoding.must_equal '011000101001110011001010011101111010110011' + assert_equal '011000101001110011001010011101111010110011', @code.left_encoding end it "should have the expected right_encoding" do - @code.right_encoding.must_equal '100001011001101100110100001011100101110100' + assert_equal '100001011001101100110100001011100101110100', @code.right_encoding end it "should have the expected encoding" do - #Start Left Center Right Stop - @code.encoding.must_equal '101' + '011000101001110011001010011101111010110011' + '01010' + '100001011001101100110100001011100101110100' + '101' + # Start Left Center Right Stop + assert_equal '101' + '011000101001110011001010011101111010110011' + '01010' + '100001011001101100110100001011100101110100' + '101', @code.encoding end end describe 'static data' do before :each do @code = EAN13.new('123456789012') end it "should have the expected start_encoding" do - @code.start_encoding.must_equal '101' + assert_equal '101', @code.start_encoding end it "should have the expected stop_encoding" do - @code.stop_encoding.must_equal '101' + assert_equal '101', @code.stop_encoding end it "should have the expected center_encoding" do - @code.center_encoding.must_equal '01010' + assert_equal '01010', @code.center_encoding end end end diff --git a/test/ean8_test.rb b/test/ean8_test.rb index db72edd..eaa735d 100644 --- a/test/ean8_test.rb +++ b/test/ean8_test.rb @@ -1,100 +1,100 @@ require 'test_helper' require 'barby/barcode/ean_8' class EAN8Test < Barby::TestCase describe 'validations' do before do @valid = EAN8.new('1234567') end it "should be valid with 7 digits" do assert @valid.valid? end it "should not be valid with less than 7 digits" do @valid.data = '123456' refute @valid.valid? end it "should not be valid with more than 7 digits" do @valid.data = '12345678' refute @valid.valid? end it "should not be valid with non-digits" do @valid.data = 'abcdefg' refute @valid.valid? end end describe 'checksum' do before :each do @code = EAN8.new('5512345') end it "should have the expected weighted_sum" do - @code.weighted_sum.must_equal 53 + assert_equal 53, @code.weighted_sum end it "should have the expected checksum" do - @code.checksum.must_equal 7 + assert_equal 7, @code.checksum end end describe 'data' do before :each do @data = '5512345' @code = EAN8.new(@data) end it "should have the expected data" do - @code.data.must_equal @data + assert_equal @data, @code.data end it "should have the expected odd_and_even_numbers" do - @code.odd_and_even_numbers.must_equal [[5,3,1,5],[4,2,5]] + assert_equal [[5,3,1,5],[4,2,5]], @code.odd_and_even_numbers end it "should have the expected left_numbers" do #EAN-8 includes the first character in the left-hand encoding, unlike EAN-13 - @code.left_numbers.must_equal [5,5,1,2] + assert_equal [5,5,1,2], @code.left_numbers end it "should have the expected right_numbers" do - @code.right_numbers.must_equal [3,4,5,7] + assert_equal [3,4,5,7], @code.right_numbers end it "should return the data with checksum on to_s" do - @code.to_s.must_equal '55123457' + assert_equal '55123457', @code.to_s end end describe 'encoding' do before :each do @code = EAN8.new('5512345') end it "should have the expected left_parity_map" do - @code.left_parity_map.must_equal [:odd, :odd, :odd, :odd] + assert_equal [:odd, :odd, :odd, :odd], @code.left_parity_map end it "should have the expected left_encoding" do - @code.left_encoding.must_equal '0110001011000100110010010011' + assert_equal '0110001011000100110010010011', @code.left_encoding end it "should have the expected right_encoding" do - @code.right_encoding.must_equal '1000010101110010011101000100' + assert_equal '1000010101110010011101000100', @code.right_encoding end end end diff --git a/test/outputter/cairo_outputter_test.rb b/test/outputter/cairo_outputter_test.rb index 99d45cc..17ffb1a 100644 --- a/test/outputter/cairo_outputter_test.rb +++ b/test/outputter/cairo_outputter_test.rb @@ -1,129 +1,131 @@ require 'test_helper' class CairoOutputterTest < Barby::TestCase - + def ps_available? Cairo.const_defined?(:PSSurface) end def eps_available? ps_available? and Cairo::PSSurface.method_defined?(:eps=) end def pdf_available? Cairo.const_defined?(:PDFSurface) end def svg_available? Cairo.const_defined?(:SVGSurface) end before do load_outputter('cairo') @barcode = Barby::Barcode.new def @barcode.encoding; '101100111000'; end @outputter = Barby::CairoOutputter.new(@barcode) @outputters = Barby::Barcode.outputters @surface = Cairo::ImageSurface.new(100, 100) @context = Cairo::Context.new(@surface) end it "should have defined the render_to_cairo_context method" do - @outputters.must_include(:render_to_cairo_context) + assert @outputters.include?(:render_to_cairo_context) end it "should have defined the to_png method" do - @outputters.must_include(:to_png) + assert @outputters.include?(:to_png) end it "should have defined the to_ps and to_eps method if available" do if ps_available? - @outputters.must_include(:to_ps) + assert @outputters.include?(:to_ps) if eps_available? - @outputters.must_include(:to_eps) + assert @outputters.include?(:to_eps) else - @outputters.wont_include(:to_eps) + refute @outputters.include?(:to_eps) end else - @outputters.wont_include(:to_ps) - @outputters.wont_include(:to_eps) + refute @outputters.include?(:to_ps) + refute @outputters.include?(:to_eps) end end it "should have defined the to_pdf method if available" do if pdf_available? - @outputters.must_include(:to_pdf) + assert @outputters.include?(:to_pdf) else - @outputters.wont_include(:to_pdf) + refute @outputters.include?(:to_pdf) end end it "should have defined the to_svg method if available" do if svg_available? - @outputters.must_include(:to_svg) + assert @outputters.include?(:to_svg) else - @outputters.wont_include(:to_svg) + refute @outputters.include?(:to_svg) end end it "should return the cairo context object it was given in render_to_cairo_context" do - @barcode.render_to_cairo_context(@context).object_id.must_equal @context.object_id + assert_equal @context.object_id, @barcode.render_to_cairo_context(@context).object_id end it "should return PNG image by the to_png method" do png = @barcode.to_png data = ruby_19_or_greater? ? png.force_encoding('BINARY') : png - data.must_match(/\A\x89PNG/n) + assert_match /\A\x89PNG/n, data end it "should return PS document by the to_ps method" do if ps_available? - @barcode.to_ps.must_match(/\A%!PS-Adobe-[\d.]/) + assert_match /\A%!PS-Adobe-[\d.]/, @barcode.to_ps end end it "should return EPS document by the to_eps method" do if eps_available? - @barcode.to_eps.must_match(/\A%!PS-Adobe-[\d.]+ EPSF-[\d.]+/) + assert_match /\A%!PS-Adobe-[\d.]+ EPSF-[\d.]+/, @barcode.to_eps end end it "should return PDF document by the to_pdf method" do if pdf_available? pdf = @barcode.to_pdf data = ruby_19_or_greater? ? pdf.force_encoding('BINARY') : pdf - data.must_match(/\A%PDF-[\d.]+/n) + assert_match /\A%PDF-[\d.]+/n, data end end it "should return SVG document by the to_svg method" do if svg_available? - @barcode.to_svg.must_match(/<\/svg>\s*\Z/m) + assert_match /<\/svg>\s*\Z/m, @barcode.to_svg end end it "should have x, y, width, height, full_width, full_height, xdim and margin attributes" do - @outputter.must_respond_to(:x) - @outputter.must_respond_to(:y) - @outputter.must_respond_to(:width) - @outputter.must_respond_to(:height) - @outputter.must_respond_to(:full_width) - @outputter.must_respond_to(:full_height) - @outputter.must_respond_to(:xdim) - @outputter.must_respond_to(:margin) + assert @outputter.respond_to?(:x) + assert @outputter.respond_to?(:y) + assert @outputter.respond_to?(:width) + assert @outputter.respond_to?(:height) + assert @outputter.respond_to?(:full_width) + assert @outputter.respond_to?(:full_height) + assert @outputter.respond_to?(:xdim) + assert @outputter.respond_to?(:margin) end it "should not change attributes when given an options hash to render" do %w(x y height xdim).each do |m| @outputter.send("#{m}=", 10) - @outputter.send(m).must_equal 10 + assert_equal 10, @outputter.send(m) end @outputter.render_to_cairo_context(@context, :x => 20, :y => 20, :height => 20, :xdim => 20) - %w(x y height xdim).each{|m| @outputter.send(m).must_equal 10 } + %w(x y height xdim).each do |m| + assert_equal 10, @outputter.send(m) + end end - + end diff --git a/test/outputter/html_outputter_test.rb b/test/outputter/html_outputter_test.rb index 65c3bb9..80273ec 100644 --- a/test/outputter/html_outputter_test.rb +++ b/test/outputter/html_outputter_test.rb @@ -1,68 +1,67 @@ require 'test_helper' require 'barby/barcode/code_128' -#require 'barby/outputter/html_outputter' class HtmlOutputterTest < Barby::TestCase class MockCode attr_reader :encoding def initialize(e) @encoding = e end def two_dimensional? encoding.is_a? Array end end before do load_outputter('html') @barcode = Barby::Code128B.new('BARBY') @outputter = HtmlOutputter.new(@barcode) end it "should register to_html" do - Barcode.outputters.must_include(:to_html) + assert Barcode.outputters.include?(:to_html) end it 'should have the expected start HTML' do assert_equal '<table class="barby-barcode"><tbody>', @outputter.start end it 'should be able to set additional class name' do @outputter.class_name = 'humbaba' assert_equal '<table class="barby-barcode humbaba"><tbody>', @outputter.start end it 'should have the expected stop HTML' do assert_equal '</tbody></table>', @outputter.stop end it 'should build the expected cells' do assert_equal ['<td class="barby-cell on"></td>', '<td class="barby-cell off"></td>', '<td class="barby-cell off"></td>', '<td class="barby-cell on"></td>'], @outputter.cells_for([true, false, false, true]) end it 'should build the expected rows' do assert_equal( [ "<tr class=\"barby-row\">#{@outputter.cells_for([true, false]).join}</tr>", "<tr class=\"barby-row\">#{@outputter.cells_for([false, true]).join}</tr>", ], @outputter.rows_for([[true, false],[false, true]]) ) end it 'should have the expected rows' do barcode = MockCode.new('101100') outputter = HtmlOutputter.new(barcode) assert_equal outputter.rows_for([[true, false, true, true, false, false]]), outputter.rows barcode = MockCode.new(['101', '010']) outputter = HtmlOutputter.new(barcode) assert_equal outputter.rows_for([[true, false, true], [false, true, false]]), outputter.rows end it 'should have the expected html' do assert_equal @outputter.start + @outputter.rows.join + @outputter.stop, @outputter.to_html end end diff --git a/test/outputter/pdfwriter_outputter_test.rb b/test/outputter/pdfwriter_outputter_test.rb index 0e6fe9f..215eab4 100644 --- a/test/outputter/pdfwriter_outputter_test.rb +++ b/test/outputter/pdfwriter_outputter_test.rb @@ -1,37 +1,37 @@ unless RUBY_VERSION >= '1.9' require 'test_helper' require 'pdf/writer' class PDFWriterOutputterTest < Barby::TestCase before do load_outputter('pdfwriter') @barcode = Barcode.new def @barcode.encoding; '101100111000'; end @outputter = PDFWriterOutputter.new(@barcode) @pdf = PDF::Writer.new end it "should have registered annotate_pdf" do - Barcode.outputters.must_include(:annotate_pdf) + assert Barcode.outputters.include?(:annotate_pdf) end it "should have defined the annotate_pdf method" do - @outputter.must_respond_to(:annotate_pdf) + assert @outputter.respond_to?(:annotate_pdf) end it "should return the pdf object it was given in annotate_pdf" do - @barcode.annotate_pdf(@pdf).object_id.must_equal @pdf.object_id + assert_equal @pdf.object_id, @barcode.annotate_pdf(@pdf).object_id end it "should have x, y, height and xdim attributes" do - @outputter.must_respond_to(:x) - @outputter.must_respond_to(:y) - @outputter.must_respond_to(:height) - @outputter.must_respond_to(:xdim) + assert @outputter.respond_to?(:x) + assert @outputter.respond_to?(:y) + assert @outputter.respond_to?(:height) + assert @outputter.respond_to?(:xdim) end end end diff --git a/test/outputter/png_outputter_test.rb b/test/outputter/png_outputter_test.rb index d4cc918..3478cf9 100644 --- a/test/outputter/png_outputter_test.rb +++ b/test/outputter/png_outputter_test.rb @@ -1,49 +1,49 @@ require 'test_helper' class PngTestBarcode < Barby::Barcode def initialize(data) @data = data end def encoding @data end end class PngOutputterTest < Barby::TestCase before do load_outputter('png') @barcode = PngTestBarcode.new('10110011100011110000') @outputter = PngOutputter.new(@barcode) end - + it "should register to_png and to_image" do - Barcode.outputters.must_include(:to_png) - Barcode.outputters.must_include(:to_image) + assert Barcode.outputters.include?(:to_png) + assert Barcode.outputters.include?(:to_image) end it "should return a ChunkyPNG::Datastream on to_datastream" do - @barcode.to_datastream.must_be_instance_of(ChunkyPNG::Datastream) + assert @barcode.to_datastream.is_a?(ChunkyPNG::Datastream) end it "should return a string on to_png" do - @barcode.to_png.must_be_instance_of(String) + assert @barcode.to_png.is_a?(String) end it "should return a ChunkyPNG::Image on to_canvas" do - @barcode.to_image.must_be_instance_of(ChunkyPNG::Image) + assert @barcode.to_image.is_a?(ChunkyPNG::Image) end it "should have a width equal to Xdim * barcode_string.length" do - @outputter.width.must_equal @outputter.barcode.encoding.length * @outputter.xdim + assert_equal @outputter.barcode.encoding.length * @outputter.xdim, @outputter.width end it "should have a full_width which is the sum of width + (margin*2)" do - @outputter.full_width.must_equal @outputter.width + (@outputter.margin*2) + assert_equal(@outputter.width + (@outputter.margin*2), @outputter.full_width) end it "should have a full_height which is the sum of height + (margin*2)" do - @outputter.full_height.must_equal @outputter.height + (@outputter.margin*2) + assert_equal(@outputter.height + (@outputter.margin*2), @outputter.full_height) end end diff --git a/test/outputter/prawn_outputter_test.rb b/test/outputter/prawn_outputter_test.rb index 785200e..2ba3214 100644 --- a/test/outputter/prawn_outputter_test.rb +++ b/test/outputter/prawn_outputter_test.rb @@ -1,79 +1,79 @@ require 'test_helper' class PrawnOutputterTest < Barby::TestCase before do load_outputter('prawn') @barcode = Barcode.new def @barcode.encoding; '10110011100011110000'; end @outputter = PrawnOutputter.new(@barcode) end it "should register to_pdf and annotate_pdf" do - Barcode.outputters.must_include(:to_pdf) - Barcode.outputters.must_include(:annotate_pdf) + assert Barcode.outputters.include?(:to_pdf) + assert Barcode.outputters.include?(:annotate_pdf) end it "should have a to_pdf method" do - @outputter.must_respond_to(:to_pdf) + assert @outputter.respond_to?(:to_pdf) end it "should return a PDF document in a string on to_pdf" do - @barcode.to_pdf.must_be_instance_of(String) + assert @barcode.to_pdf.is_a?(String) end it "should return the same Prawn::Document on annotate_pdf" do doc = Prawn::Document.new - @barcode.annotate_pdf(doc).object_id.must_equal doc.object_id + assert_equal doc.object_id, @barcode.annotate_pdf(doc).object_id end it "should default x and y to margin value" do @outputter.margin = 123 - @outputter.x.must_equal 123 - @outputter.y.must_equal 123 + assert_equal 123, @outputter.x + assert_equal 123, @outputter.y end it "should default ydim to xdim value" do @outputter.xdim = 321 - @outputter.ydim.must_equal 321 + assert_equal 321, @outputter.ydim end it "should be able to calculate width required" do - @outputter.width.must_equal @barcode.encoding.length + assert_equal @barcode.encoding.length, @outputter.width @outputter.xdim = 2 - @outputter.width.must_equal @barcode.encoding.length * 2 - @outputter.full_width.must_equal @barcode.encoding.length * 2 + assert_equal @barcode.encoding.length * 2, @outputter.width + assert_equal @barcode.encoding.length * 2, @outputter.full_width @outputter.margin = 5 - @outputter.full_width.must_equal((@barcode.encoding.length * 2) + 10) + assert_equal((@barcode.encoding.length * 2) + 10, @outputter.full_width) #2D barcode = Barcode2D.new def barcode.encoding; ['111', '000', '111'] end outputter = PrawnOutputter.new(barcode) - outputter.width.must_equal 3 + assert_equal 3, outputter.width outputter.xdim = 2 outputter.margin = 5 - outputter.width.must_equal 6 - outputter.full_width.must_equal 16 + assert_equal 6, outputter.width + assert_equal 16, outputter.full_width end it "should be able to calculate height required" do - @outputter.full_height.must_equal @outputter.height + assert_equal @outputter.height, @outputter.full_height @outputter.margin = 5 - @outputter.full_height.must_equal @outputter.height + 10 + assert_equal @outputter.height + 10, @outputter.full_height #2D barcode = Barcode2D.new def barcode.encoding; ['111', '000', '111'] end outputter = PrawnOutputter.new(barcode) - outputter.height.must_equal 3 + assert_equal 3, outputter.height outputter.xdim = 2 #ydim defaults to xdim outputter.margin = 5 - outputter.height.must_equal 6 - outputter.full_height.must_equal 16 + assert_equal 6, outputter.height + assert_equal 16, outputter.full_height outputter.ydim = 3 #ydim overrides xdim when set - outputter.height.must_equal 9 - outputter.full_height.must_equal 19 + assert_equal 9, outputter.height + assert_equal 19, outputter.full_height end end diff --git a/test/outputter/rmagick_outputter_test.rb b/test/outputter/rmagick_outputter_test.rb index 41870c7..73fc253 100644 --- a/test/outputter/rmagick_outputter_test.rb +++ b/test/outputter/rmagick_outputter_test.rb @@ -1,83 +1,83 @@ require 'test_helper' class RmagickTestBarcode < Barby::Barcode def initialize(data) @data = data end def encoding @data end end class RmagickOutputterTest < Barby::TestCase before do load_outputter('rmagick') @barcode = RmagickTestBarcode.new('10110011100011110000') @outputter = RmagickOutputter.new(@barcode) end it "should register to_png, to_gif, to_jpg, to_image" do - Barcode.outputters.must_include(:to_png) - Barcode.outputters.must_include(:to_gif) - Barcode.outputters.must_include(:to_jpg) - Barcode.outputters.must_include(:to_image) + assert Barcode.outputters.include?(:to_png) + assert Barcode.outputters.include?(:to_gif) + assert Barcode.outputters.include?(:to_jpg) + assert Barcode.outputters.include?(:to_image) end it "should have defined to_png, to_gif, to_jpg, to_image" do - @outputter.must_respond_to(:to_png) - @outputter.must_respond_to(:to_gif) - @outputter.must_respond_to(:to_jpg) - @outputter.must_respond_to(:to_image) + assert @outputter.respond_to?(:to_png) + assert @outputter.respond_to?(:to_gif) + assert @outputter.respond_to?(:to_jpg) + assert @outputter.respond_to?(:to_image) end it "should return a string on to_png and to_gif" do - @outputter.to_png.must_be_instance_of(String) - @outputter.to_gif.must_be_instance_of(String) + assert @outputter.to_png.is_a?(String) + assert @outputter.to_gif.is_a?(String) end it "should return a Magick::Image instance on to_image" do - @outputter.to_image.must_be_instance_of(Magick::Image) + assert @outputter.to_image.is_a?(Magick::Image) end it "should have a width equal to the length of the barcode encoding string * x dimension" do - @outputter.xdim.must_equal 1#Default - @outputter.width.must_equal @outputter.barcode.encoding.length + assert_equal 1, @outputter.xdim #Default + assert_equal @outputter.barcode.encoding.length, @outputter.width @outputter.xdim = 2 - @outputter.width.must_equal @outputter.barcode.encoding.length * 2 + assert_equal @outputter.barcode.encoding.length * 2, @outputter.width end it "should have a full_width equal to the width + left and right margins" do - @outputter.xdim.must_equal 1 - @outputter.margin.must_equal 10 - @outputter.full_width.must_equal (@outputter.width + 10 + 10) + assert_equal 1, @outputter.xdim + assert_equal 10, @outputter.margin + assert_equal((@outputter.width + 10 + 10), @outputter.full_width) end it "should have a default height of 100" do - @outputter.height.must_equal 100 + assert_equal 100, @outputter.height @outputter.height = 200 - @outputter.height.must_equal 200 + assert_equal 200, @outputter.height end it "should have a full_height equal to the height + top and bottom margins" do - @outputter.full_height.must_equal @outputter.height + (@outputter.margin * 2) + assert_equal(@outputter.height + (@outputter.margin * 2), @outputter.full_height) end describe "#to_image" do before do @barcode = RmagickTestBarcode.new('10110011100011110000') @outputter = RmagickOutputter.new(@barcode) @image = @outputter.to_image end it "should have a width and height equal to the outputter's full_width and full_height" do - @image.columns.must_equal @outputter.full_width - @image.rows.must_equal @outputter.full_height + assert_equal @outputter.full_width, @image.columns + assert_equal @outputter.full_height, @image.rows end end end diff --git a/test/outputter/svg_outputter_test.rb b/test/outputter/svg_outputter_test.rb index 3740960..55cf994 100644 --- a/test/outputter/svg_outputter_test.rb +++ b/test/outputter/svg_outputter_test.rb @@ -1,89 +1,90 @@ require 'test_helper' class SvgBarcode < Barby::Barcode attr_accessor :data, :two_d def initialize(data, two_d=false) self.data, self.two_d = data, two_d end def encoding data end def two_dimensional? two_d end def to_s data end end + class SvgOutputterTest < Barby::TestCase - + before do load_outputter('svg') @barcode = SvgBarcode.new('10110011100011110000') @outputter = SvgOutputter.new(@barcode) end it 'should register to_svg, bars_to_rects, and bars_to_path' do - Barcode.outputters.must_include :to_svg - Barcode.outputters.must_include :bars_to_rects - Barcode.outputters.must_include :bars_to_path + assert Barcode.outputters.include?(:to_svg) + assert Barcode.outputters.include?(:bars_to_rects) + assert Barcode.outputters.include?(:bars_to_path) end it 'should return a string on to_svg' do - @barcode.to_svg.must_be_instance_of String + assert @barcode.to_svg.is_a?(String) end - + it 'should return a string on bars_to_rects' do - @barcode.bars_to_rects.must_be_instance_of String + assert @barcode.bars_to_rects.is_a?(String) end - + it 'should return a string on bars_to_path' do - @barcode.bars_to_path.must_be_instance_of String + assert @barcode.bars_to_path.is_a?(String) end - + it 'should produce one rect for each bar' do - @barcode.bars_to_rects.scan(/<rect/).size.must_equal @outputter.send(:boolean_groups).select{|bg|bg[0]}.size + assert_equal @outputter.send(:boolean_groups).select{|bg|bg[0]}.size, @barcode.bars_to_rects.scan(/<rect/).size end - + it 'should produce one path stroke for each bar module' do - @barcode.bars_to_path.scan(/(M\d+\s+\d+)\s*(V\d+)/).size.must_equal @outputter.send(:booleans).select{|bg|bg}.size + assert_equal @outputter.send(:booleans).select{|bg|bg}.size, @barcode.bars_to_path.scan(/(M\d+\s+\d+)\s*(V\d+)/).size end - + it 'should return default values for attributes' do - @outputter.margin.must_be_instance_of Fixnum + assert @outputter.margin.is_a?(Integer) end - + it 'should use defaults to populate higher level attributes' do - @outputter.xmargin.must_equal @outputter.margin + assert_equal @outputter.margin, @outputter.xmargin end - + it 'should return nil for overridden attributes' do @outputter.xmargin = 1 - @outputter.margin.must_equal nil + assert_equal nil, @outputter.margin end - + it 'should still use defaults for unspecified attributes' do @outputter.xmargin = 1 - @outputter.ymargin.must_equal @outputter.send(:_margin) + assert_equal @outputter.send(:_margin), @outputter.ymargin end - + it 'should have a width equal to Xdim * barcode_string.length' do - @outputter.width.must_equal @outputter.barcode.encoding.length * @outputter.xdim + assert_equal @outputter.barcode.encoding.length * @outputter.xdim, @outputter.width end - + it 'should have a full_width which is by default the sum of width + (margin*2)' do - @outputter.full_width.must_equal @outputter.width + (@outputter.margin*2) + assert_equal(@outputter.width + (@outputter.margin*2), @outputter.full_width) end - + it 'should have a full_width which is the sum of width + xmargin + ymargin' do - @outputter.full_width.must_equal @outputter.width + @outputter.xmargin + @outputter.ymargin + assert_equal @outputter.width + @outputter.xmargin + @outputter.ymargin, @outputter.full_width end - + it 'should use Barcode#to_s for title' do - @outputter.title.must_equal @barcode.data + assert_equal @barcode.data, @outputter.title def @barcode.to_s; "the eastern star"; end - @outputter.title.must_equal "the eastern star" + assert_equal "the eastern star", @outputter.title end - + end diff --git a/test/outputter_test.rb b/test/outputter_test.rb index 8c36f91..dfebe66 100644 --- a/test/outputter_test.rb +++ b/test/outputter_test.rb @@ -1,134 +1,132 @@ require 'test_helper' class OutputterTest < Barby::TestCase before do @outputter = Class.new(Outputter) end it "should be able to register an output method for barcodes" do @outputter.register :foo Barcode.outputters.must_include(:foo) @outputter.register :bar, :baz Barcode.outputters.must_include(:bar) Barcode.outputters.must_include(:baz) @outputter.register :quux => :my_quux Barcode.outputters.must_include(:quux) end - + describe "Outputter instances" do before do @barcode = Barcode.new class << @barcode; attr_accessor :encoding; end @barcode.encoding = '101100111000' @outputter = Outputter.new(@barcode) end it "should have a method 'booleans' which converts the barcode encoding to an array of true,false values" do - @outputter.send(:booleans).length.must_equal @barcode.encoding.length + assert_equal @barcode.encoding.length, @outputter.send(:booleans).length t, f = true, false - @outputter.send(:booleans).must_equal [t,f,t,t,f,f,t,t,t,f,f,f] + assert_equal [t,f,t,t,f,f,t,t,t,f,f,f], @outputter.send(:booleans) end it "should convert 2D encodings with 'booleans'" do barcode = Barcode2D.new def barcode.encoding; ['101100','110010']; end outputter = Outputter.new(barcode) - outputter.send(:booleans).length.must_equal barcode.encoding.length + assert_equal barcode.encoding.length, outputter.send(:booleans).length t, f = true, false - outputter.send(:booleans).must_equal [[t,f,t,t,f,f], [t,t,f,f,t,f]] + assert_equal [[t,f,t,t,f,f], [t,t,f,f,t,f]], outputter.send(:booleans) end it "should have an 'encoding' attribute" do - @outputter.send(:encoding).must_equal @barcode.encoding + assert_equal @barcode.encoding, @outputter.send(:encoding) end it "should cache encoding" do - @outputter.send(:encoding).must_equal @barcode.encoding + assert_equal @barcode.encoding, @outputter.send(:encoding) previous_encoding = @barcode.encoding @barcode.encoding = '101010' - @outputter.send(:encoding).must_equal previous_encoding - @outputter.send(:encoding, true).must_equal @barcode.encoding + assert_equal previous_encoding, @outputter.send(:encoding) + assert_equal @barcode.encoding, @outputter.send(:encoding, true) end it "should have a boolean_groups attribute which collects continuous bars and spaces" do t, f = true, false # 1 0 11 00 111 000 - @outputter.send(:boolean_groups).must_equal [[t,1],[f,1],[t,2],[f,2],[t,3],[f,3]] + assert_equal [[t,1],[f,1],[t,2],[f,2],[t,3],[f,3]], @outputter.send(:boolean_groups) barcode = Barcode2D.new def barcode.encoding; ['1100', '111000']; end outputter = Outputter.new(barcode) - outputter.send(:boolean_groups).must_equal [[[t,2],[f,2]],[[t,3],[f,3]]] + assert_equal [[[t,2],[f,2]],[[t,3],[f,3]]], outputter.send(:boolean_groups) end it "should have a with_options method which sets the instance's attributes temporarily while the block gets yielded" do class << @outputter; attr_accessor :foo, :bar; end @outputter.foo, @outputter.bar = 'humbaba', 'scorpion man' @outputter.send(:with_options, :foo => 'horse', :bar => 'donkey') do - @outputter.foo.must_equal 'horse' - @outputter.bar.must_equal 'donkey' + assert_equal 'horse', @outputter.foo + assert_equal 'donkey', @outputter.bar end - @outputter.foo.must_equal 'humbaba' - @outputter.bar.must_equal 'scorpion man' + assert_equal 'humbaba', @outputter.foo + assert_equal 'scorpion man', @outputter.bar end it "should return the block value on with_options" do - @outputter.send(:with_options, {}){ 'donkey' }.must_equal 'donkey' + assert_equal 'donkey', @outputter.send(:with_options, {}){ 'donkey' } end it "should have a two_dimensional? method which returns true if the barcode is 2d" do refute Outputter.new(Barcode1D.new).send(:two_dimensional?) assert Outputter.new(Barcode2D.new).send(:two_dimensional?) end it "should not require the barcode object to respond to two_dimensional?" do barcode = Object.new def barcode.encoding; "101100111000"; end outputter = Outputter.new(barcode) assert outputter.send(:booleans) assert outputter.send(:boolean_groups) end end describe "Barcode instances" do - + before do @outputter = Class.new(Outputter) @outputter.register :foo @outputter.register :bar => :my_bar @outputter.class_eval{ def foo; 'foo'; end; def my_bar; 'bar'; end } @barcode = Barcode.new end - + it "should respond to registered output methods" do - @barcode.foo.must_equal 'foo' - @barcode.bar.must_equal 'bar' + assert_equal 'foo', @barcode.foo + assert_equal 'bar', @barcode.bar end - + it "should send arguments to registered method on outputter class" do @outputter.class_eval{ def foo(*a); a; end; def my_bar(*a); a; end } - @barcode.foo(1,2,3).must_equal [1,2,3] - @barcode.bar('humbaba').must_equal ['humbaba'] + assert_equal [1,2,3], @barcode.foo(1,2,3) + assert_equal ['humbaba'], @barcode.bar('humbaba') end - + it "should pass block to registered methods" do @outputter.class_eval{ def foo(*a, &b); b.call(*a); end } - @barcode.foo(1,2,3){|*a| a }.must_equal [1,2,3] + assert_equal [1,2,3], @barcode.foo(1,2,3){|*a| a } end - + it "should be able to get an instance of a specific outputter" do - @barcode.outputter_for(:foo).must_be_instance_of(@outputter) + assert @barcode.outputter_for(:foo).is_a?(@outputter) end - + it "should be able to get a specific outputter class" do - @barcode.outputter_class_for(:foo).must_equal @outputter + assert_equal @outputter, @barcode.outputter_class_for(:foo) end - + end end - - diff --git a/test/pdf_417_test.rb b/test/pdf_417_test.rb index 7221b39..e263755 100644 --- a/test/pdf_417_test.rb +++ b/test/pdf_417_test.rb @@ -1,45 +1,45 @@ if defined? JRUBY_VERSION require 'test_helper' require 'barby/barcode/pdf_417' class Pdf417Test < Barby::TestCase - + it "should produce a nice code" do enc = Pdf417.new('Ereshkigal').encoding - enc.must_equal [ + assert_equal [ "111111111101010100101111010110011110100111010110001110100011101101011100100001111111101000110100100", - "111111111101010100101111010110000100100110100101110000101011111110101001111001111111101000110100100", + "111111111101010100101111010110000100100110100101110000101011111110101001111001111111101000110100100", "111111111101010100101101010111111000100100011100110011111010101100001111100001111111101000110100100", - "111111111101010100101111101101111110110100010100011101111011010111110111111001111111101000110100100", - "111111111101010100101101011110000010100110010101110010100011101101110001110001111111101000110100100", - "111111111101010100101111101101110000110101101100000011110011110110111110111001111111101000110100100", - "111111111101010100101101001111001111100110001101001100100010100111101110100001111111101000110100100", - "111111111101010100101111110110010111100111100100101000110010101111111001111001111111101000110100100", - "111111111101010100101010011101111100100101111110001110111011111101001110110001111111101000110100100", - "111111111101010100101010001111011100100100111110111110111010100101100011100001111111101000110100100", - "111111111101010100101101001111000010100110001101110000101011101100111001110001111111101000110100100", - "111111111101010100101101000110011111100101111111011101100011111110100011100101111111101000110100100", - "111111111101010100101010000101010000100100011100001100101010100100110000111001111111101000110100100", - "111111111101010100101111010100100001100100010100111100101011110110001001100001111111101000110100100", + "111111111101010100101111101101111110110100010100011101111011010111110111111001111111101000110100100", + "111111111101010100101101011110000010100110010101110010100011101101110001110001111111101000110100100", + "111111111101010100101111101101110000110101101100000011110011110110111110111001111111101000110100100", + "111111111101010100101101001111001111100110001101001100100010100111101110100001111111101000110100100", + "111111111101010100101111110110010111100111100100101000110010101111111001111001111111101000110100100", + "111111111101010100101010011101111100100101111110001110111011111101001110110001111111101000110100100", + "111111111101010100101010001111011100100100111110111110111010100101100011100001111111101000110100100", + "111111111101010100101101001111000010100110001101110000101011101100111001110001111111101000110100100", + "111111111101010100101101000110011111100101111111011101100011111110100011100101111111101000110100100", + "111111111101010100101010000101010000100100011100001100101010100100110000111001111111101000110100100", + "111111111101010100101111010100100001100100010100111100101011110110001001100001111111101000110100100", "111111111101010100101111010100011110110110011111101001100010100100001001111101111111101000110100100" - ] - enc.length.must_equal 15 - enc[0].length.must_equal 99 + ], enc + assert_equal 15, enc.length + assert_equal 99, enc[0].length end it "should produce a 19x135 code with default aspect_ratio" do enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3).encoding - enc.length.must_equal 19 - enc[0].length.must_equal 135 + assert_equal 19, enc.length + assert_equal 135, enc[0].length end it "should produce a 29x117 code with 0.7 aspect_ratio" do - enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3, :aspect_ratio => 0.7).encoding - enc.length.must_equal 29 - enc[0].length.must_equal 117 + enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3, aspect_ratio: 0.7).encoding + assert_equal 29, enc.length + assert_equal 117, enc[0].length end - + end end diff --git a/test/qr_code_test.rb b/test/qr_code_test.rb index fc20644..ec87748 100644 --- a/test/qr_code_test.rb +++ b/test/qr_code_test.rb @@ -1,78 +1,83 @@ require 'test_helper' require 'barby/barcode/qr_code' class QrCodeTest < Barby::TestCase before do @data = 'Ereshkigal' @code = QrCode.new(@data) end it "should have the expected data" do - @code.data.must_equal @data + assert_equal @data, @code.data end it "should have the expected encoding" do # Should be an array of strings, where each string represents a "line" - @code.encoding.must_equal(rqrcode(@code).modules.map do |line| + expected = rqrcode(@code).modules.map do |line| line.inject(''){|s,m| s << (m ? '1' : '0') } - end) + end + assert_equal expected, @code.encoding end - + it "should be able to change its data and output a different encoding" do @code.data = 'hades' - @code.data.must_equal 'hades' - @code.encoding.must_equal(rqrcode(@code).modules.map do |line| + assert_equal 'hades', @code.data + expected = rqrcode(@code).modules.map do |line| line.inject(''){|s,m| s << (m ? '1' : '0') } - end) + end + assert_equal expected, @code.encoding end - + it "should have a 'level' accessor" do - @code.must_respond_to :level - @code.must_respond_to :level= + assert @code.respond_to?(:level) + assert @code.respond_to?(:level=) end - + it "should set size according to size of data" do - QrCode.new('1'*15, :level => :l).size.must_equal 1 - QrCode.new('1'*15, :level => :m).size.must_equal 2 - QrCode.new('1'*15, :level => :q).size.must_equal 2 - QrCode.new('1'*15, :level => :h).size.must_equal 3 - - QrCode.new('1'*30, :level => :l).size.must_equal 2 - QrCode.new('1'*30, :level => :m).size.must_equal 3 - QrCode.new('1'*30, :level => :q).size.must_equal 3 - QrCode.new('1'*30, :level => :h).size.must_equal 4 - - QrCode.new('1'*270, :level => :l).size.must_equal 10 + assert_equal 1, QrCode.new('1'*15, level: :l).size + assert_equal 2, QrCode.new('1'*15, level: :m).size + assert_equal 2, QrCode.new('1'*15, level: :q).size + assert_equal 3, QrCode.new('1'*15, level: :h).size + + assert_equal 2, QrCode.new('1'*30, level: :l).size + assert_equal 3, QrCode.new('1'*30, level: :m).size + assert_equal 3, QrCode.new('1'*30, level: :q).size + assert_equal 4, QrCode.new('1'*30, level: :h).size + + assert_equal 10, QrCode.new('1'*270, level: :l).size end - + it "should allow size to be set manually" do - code = QrCode.new('1'*15, :level => :l, :size => 2) - code.size.must_equal 2 - code.encoding.must_equal(rqrcode(code).modules.map do |line| + code = QrCode.new('1'*15, level: :l, size: 2) + assert_equal 2, code.size + expected = rqrcode(code).modules.map do |line| line.inject(''){|s,m| s << (m ? '1' : '0') } - end) + end + assert_equal expected, code.encoding end - + it "should raise ArgumentError when data too large" do - assert QrCode.new('1'*2953, :level => :l) - lambda{ QrCode.new('1'*2954, :level => :l) }.must_raise ArgumentError + QrCode.new('1'*2953, level: :l) + assert_raises ArgumentError do + QrCode.new('1'*2954, level: :l) + end end - + it "should return the original data on to_s" do - @code.to_s.must_equal 'Ereshkigal' + assert_equal 'Ereshkigal', @code.to_s end - + it "should include at most 20 characters on to_s" do - QrCode.new('123456789012345678901234567890').to_s.must_equal '12345678901234567890' + assert_equal '12345678901234567890', QrCode.new('123456789012345678901234567890').to_s end - + private - + def rqrcode(code) - RQRCode::QRCode.new(code.data, :level => code.level, :size => code.size) + RQRCode::QRCode.new(code.data, level: code.level, size: code.size) end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 09f7db5..68846fd 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,24 +1,24 @@ require 'rubygems' require 'barby' require 'minitest/autorun' require 'minitest/spec' module Barby - class TestCase < MiniTest::Spec + class TestCase < Minitest::Spec include Barby private # So we can register outputter during an full test suite run. def load_outputter(outputter) @loaded_outputter ||= load "barby/outputter/#{outputter}_outputter.rb" rescue LoadError => e skip "#{outputter} not being installed properly" end def ruby_19_or_greater? RUBY_VERSION >= '1.9' end end end diff --git a/test/upc_supplemental_test.rb b/test/upc_supplemental_test.rb index 3776fa7..c3625be 100644 --- a/test/upc_supplemental_test.rb +++ b/test/upc_supplemental_test.rb @@ -1,109 +1,109 @@ require 'test_helper' require 'barby/barcode/upc_supplemental' class UpcSupplementalTest < Barby::TestCase it 'should be valid with 2 or 5 digits' do assert UPCSupplemental.new('12345').valid? assert UPCSupplemental.new('12').valid? end it 'should not be valid with any number of digits other than 2 or 5' do refute UPCSupplemental.new('1234').valid? refute UPCSupplemental.new('123').valid? refute UPCSupplemental.new('1').valid? refute UPCSupplemental.new('123456').valid? refute UPCSupplemental.new('123456789012').valid? end it 'should not be valid with non-digit characters' do refute UPCSupplemental.new('abcde').valid? refute UPCSupplemental.new('ABC').valid? refute UPCSupplemental.new('1234e').valid? refute UPCSupplemental.new('!2345').valid? refute UPCSupplemental.new('ab').valid? refute UPCSupplemental.new('1b').valid? refute UPCSupplemental.new('a1').valid? end - + describe 'checksum for 5 digits' do - + it 'should have the expected odd_digits' do - UPCSupplemental.new('51234').odd_digits.must_equal [4,2,5] - UPCSupplemental.new('54321').odd_digits.must_equal [1,3,5] - UPCSupplemental.new('99990').odd_digits.must_equal [0,9,9] + assert_equal [4,2,5], UPCSupplemental.new('51234').odd_digits + assert_equal [1,3,5], UPCSupplemental.new('54321').odd_digits + assert_equal [0,9,9], UPCSupplemental.new('99990').odd_digits end it 'should have the expected even_digits' do - UPCSupplemental.new('51234').even_digits.must_equal [3,1] - UPCSupplemental.new('54321').even_digits.must_equal [2,4] - UPCSupplemental.new('99990').even_digits.must_equal [9,9] + assert_equal [3,1], UPCSupplemental.new('51234').even_digits + assert_equal [2,4], UPCSupplemental.new('54321').even_digits + assert_equal [9,9], UPCSupplemental.new('99990').even_digits end it 'should have the expected odd and even sums' do - UPCSupplemental.new('51234').odd_sum.must_equal 33 - UPCSupplemental.new('54321').odd_sum.must_equal 27 - UPCSupplemental.new('99990').odd_sum.must_equal 54 + assert_equal 33, UPCSupplemental.new('51234').odd_sum + assert_equal 27, UPCSupplemental.new('54321').odd_sum + assert_equal 54, UPCSupplemental.new('99990').odd_sum - UPCSupplemental.new('51234').even_sum.must_equal 36 - UPCSupplemental.new('54321').even_sum.must_equal 54 - UPCSupplemental.new('99990').even_sum.must_equal 162 + assert_equal 36, UPCSupplemental.new('51234').even_sum + assert_equal 54, UPCSupplemental.new('54321').even_sum + assert_equal 162, UPCSupplemental.new('99990').even_sum end it 'should have the expected checksum' do - UPCSupplemental.new('51234').checksum.must_equal 9 - UPCSupplemental.new('54321').checksum.must_equal 1 - UPCSupplemental.new('99990').checksum.must_equal 6 + assert_equal 9, UPCSupplemental.new('51234').checksum + assert_equal 1, UPCSupplemental.new('54321').checksum + assert_equal 6, UPCSupplemental.new('99990').checksum end - + end - + describe 'checksum for 2 digits' do - + it 'should have the expected checksum' do - UPCSupplemental.new('51').checksum.must_equal 3 - UPCSupplemental.new('21').checksum.must_equal 1 - UPCSupplemental.new('99').checksum.must_equal 3 + assert_equal 3, UPCSupplemental.new('51').checksum + assert_equal 1, UPCSupplemental.new('21').checksum + assert_equal 3, UPCSupplemental.new('99').checksum end - + end - + describe 'encoding' do before do @data = '51234' @code = UPCSupplemental.new(@data) end it 'should have the expected encoding' do - # START 5 1 2 3 4 - UPCSupplemental.new('51234').encoding.must_equal '1011 0110001 01 0011001 01 0011011 01 0111101 01 0011101'.tr(' ', '') - # 9 9 9 9 0 - UPCSupplemental.new('99990').encoding.must_equal '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') - # START 5 1 - UPCSupplemental.new('51').encoding.must_equal '1011 0111001 01 0110011'.tr(' ', '') - # 2 2 - UPCSupplemental.new('22').encoding.must_equal '1011 0011011 01 0010011'.tr(' ', '') + # START 5 1 2 3 4 + assert_equal '1011 0110001 01 0011001 01 0011011 01 0111101 01 0011101'.tr(' ', ''), UPCSupplemental.new('51234').encoding + # 9 9 9 9 0 + assert_equal '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', ''), UPCSupplemental.new('99990').encoding + # START 5 1 + assert_equal '1011 0111001 01 0110011'.tr(' ', ''), UPCSupplemental.new('51').encoding + # 2 2 + assert_equal '1011 0011011 01 0010011'.tr(' ', ''), UPCSupplemental.new('22').encoding end it 'should be able to change its data' do prev_encoding = @code.encoding @code.data = '99990' - @code.encoding.wont_equal prev_encoding - # 9 9 9 9 0 - @code.encoding.must_equal '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') + refute_equal prev_encoding, @code.encoding + # 9 9 9 9 0 + assert_equal '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', ''), @code.encoding prev_encoding = @code.encoding @code.data = '22' - @code.encoding.wont_equal prev_encoding - # 2 2 - @code.encoding.must_equal '1011 0011011 01 0010011'.tr(' ', '') + refute_equal prev_encoding, @code.encoding + # 2 2 + assert_equal '1011 0011011 01 0010011'.tr(' ', ''), @code.encoding end end end
toretore/barby
09274406abf0ffad8cd031ed883caeef12c9ec12
Swap semacode for dmtx
diff --git a/CHANGELOG b/CHANGELOG index 6bbaf13..0e86ed5 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,84 +1,88 @@ +* 0.7.0 + +* Swap semaocde for dmtx [ksylvest] + * 0.6.7 * RMagick outputter should use line command for lines [joshuaflanagan] * 0.6.6 * Add support for Codabar symbology [labocho] * 0.6.1 * Fix single-pixel error with RMagick [James Brink] * 0.6 * Add automatic character set to Code128 * Fix test for HtmlOutputter * 0.5.1 * Fix some encoding issues (ruby 2.0 & 1.9) * Rewrite HtmlOutputter. Not entirely backwards compatible with the previous version. * 0.5.0 * Require requirement of barcode symbologies in the same way outputters must be required before being used * 0.4.4 * Use Gemfile for dependency management [Ken Collins] * Move to MiniTest [Ken Collins] * HTML outputter [Ken Collins] * Various 1.9 fixes [Ken Collins, Dominique Ribaut] * 0.4.3 * 2- and 5-digit UPC supplements * Use ChunkyPNG for PngOutputter * 0.4.2 * ChunkyPngOutputter now renders 2D barcodes not upside down [Thanks Scient] * 0.4.1 * ChunkyPngOutputter - ChunkyPNG is a pure-Ruby PNG library * 0.4.0 * Can you tell I'm just making up version numbers as I go along? * DataMatrix (not required automatically, requires the 'semacode' gem) * Refactored PrawnOutputter a little. No more stupid options hashes + unbleed attribute * 0.3.2 * Fix bug where Code128 extras choke on newlines [Wayne Conrad] * Don't allow Code128 with empty data strings [Wayne Conrad] * Allow custom :size for QrCodes * 0.3.1 * Add support for PDF417, using Pdf417lib (JRuby only) [Aslak Hellesøy] * 0.3.0 * Make compatible with Ruby 1.9 [Chris Mowforth] * Add SvgOutputter for outputting SVGs without dependencies [Peter H. Li] * 0.2.1 * Allow QR Codes with sizes up to 40 * 0.2.0 * Added support for 2D barcodes * Updated all outputters to support 2D barcodes * Added support for QR Code * 0.1.2 * Added CairoOutputter [Kouhei Sutou] * 0.1.1 * Added PngOutputter that uses "png" gem diff --git a/README.md b/README.md index 1762a95..8cd1f56 100644 --- a/README.md +++ b/README.md @@ -1,109 +1,109 @@ # Barby Barby is a Ruby library that generates barcodes in a variety of symbologies. Its functionality is split into _barcode_ and "_outputter_" objects: * [`Barby::Barcode` objects] [symbologies] turn data into a binary representation for a given symbology. * [`Barby::Outputter`] [outputters] then takes this representation and turns it into images, PDF, etc. You can easily add a symbology without having to worry about graphical representation. If it can be represented as the usual 1D or 2D matrix of lines or squares, outputters will do that for you. Likewise, you can easily add an outputter for a format that doesn't have one yet, and it will work with all existing symbologies. For more information, check out [the Barby wiki][wiki]. ### New require policy Barcode symbologies are no longer required automatically, so you'll have to require the ones you need. If you need EAN-13, `require 'barby/barcode/ean_13'`. Full list of symbologies and filenames below. ## Example ```ruby require 'barby' require 'barby/barcode/code_128' require 'barby/outputter/ascii_outputter' barcode = Barby::Code128B.new('BARBY') puts barcode.to_ascii #Implicitly uses the AsciiOutputter ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## B A R B Y ``` ## Supported symbologies ```ruby require 'barby/barcode/<filename>' ``` | Name | Filename | Dependencies | | ----------------------------------- | --------------------- | ---------------------------------- | | Code 25 | `code_25` | ─ | | ├─ Interleaved | `code_25_interleaved` | ─ | | └─ IATA | `code_25_iata` | ─ | | Code 39 | `code_39` | ─ | | └─ Extended | `code_39` | ─ | | Code 93 | `code_93` | ─ | | Code 128 (A, B, and C) | `code_128` | ─ | | └─ GS1 128 | `gs1_128` | ─ | | Codabar | `codabar` | ─ | | EAN-13 | `ean_13` | ─ | | ├─ Bookland | `bookland` | ─ | | └─ UPC-A | `ean_13` | ─ | | EAN-8 | `ean_8` | ─ | | UPC/EAN supplemental, 2 & 5 digits | `upc_supplemental` | ─ | | QR Code | `qr_code` | `rqrcode` | -| DataMatrix (Semacode) | `data_matrix` | `semacode` or `semacode-ruby19` | +| DataMatrix (dmtx) | `data_matrix` | `dmtx` | | PDF417 | `pdf_417` | JRuby | ## Outputters ```ruby require 'barby/outputter/<filename>_outputter' ``` | filename | dependencies | | ----------- | ------------- | | `ascii` | ─ | | `cairo` | cairo | | `html` | ─ | | `pdfwriter` | ─ | | `png` | chunky_png | | `prawn` | prawn | | `rmagick` | rmagick | | `svg` | ─ | ### Formats supported by outputters * Text (mostly for testing) * PNG, JPEG, GIF * PS, EPS * SVG * PDF * HTML --- For more information, check out [the Barby wiki][wiki]. [wiki]: https://github.com/toretore/barby/wiki [symbologies]: https://github.com/toretore/barby/wiki/Symbologies [outputters]: https://github.com/toretore/barby/wiki/Outputters diff --git a/barby.gemspec b/barby.gemspec index 1ef32d5..0f7ceee 100644 --- a/barby.gemspec +++ b/barby.gemspec @@ -1,31 +1,31 @@ $:.push File.expand_path("../lib", __FILE__) require "barby/version" Gem::Specification.new do |s| s.name = "barby" s.version = Barby::VERSION::STRING s.platform = Gem::Platform::RUBY s.summary = "The Ruby barcode generator" s.email = "[email protected]" s.homepage = "http://toretore.github.com/barby" s.description = "Barby creates barcodes." s.authors = ['Tore Darell'] s.rubyforge_project = "barby" s.extra_rdoc_files = ["README.md"] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.test_files.delete("test/outputter/rmagick_outputter_test.rb") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_development_dependency "minitest", "~> 5.11" s.add_development_dependency "bundler", "~> 1.16" s.add_development_dependency "rake", "~> 10.0" - s.add_development_dependency "semacode-ruby19", "~> 0.7" s.add_development_dependency "rqrcode", "~> 0.10" s.add_development_dependency "prawn", "~> 2.2" s.add_development_dependency "cairo", "~> 1.15" + s.add_development_dependency "dmtx", "~> 0.2" end diff --git a/lib/barby/barcode/data_matrix.rb b/lib/barby/barcode/data_matrix.rb index f872a8c..f0e3812 100644 --- a/lib/barby/barcode/data_matrix.rb +++ b/lib/barby/barcode/data_matrix.rb @@ -1,46 +1,81 @@ -require 'semacode' #Ruby 1.8: gem install semacode - Ruby 1.9: gem install semacode-ruby19 +require 'dmtx' # gem install dmtx require 'barby/barcode' module Barby - #Uses the semacode library (gem install semacode) to encode DataMatrix barcodes + #Uses the dmtx library (gem install dmtx) to encode DataMatrix barcodes class DataMatrix < Barcode2D attr_reader :data def initialize(data) self.data = data end def data=(data) @data = data @encoder = nil end def encoder - @encoder ||= ::DataMatrix::Encoder.new(data) + @encoder ||= ::Dmtx::DataMatrix.new(data) end + # Converts the barcode to an array of lines where 0 is white and 1 is black. + # + # @example + # code = Barby::DataMatrix.new('humbaba') + # code.encoding + # # => [ + # # "10101010101010", + # # "10111010000001", + # # "11100101101100", + # # "11101001110001", + # # "11010101111110", + # # "11100101100001", + # # "11011001011110", + # # "10011011010011", + # # "11011010000100", + # # "10101100101001", + # # "11011100001100", + # # "10101110110111", + # # "11000001010100", + # # "11111111111111", + # # ] + # + # @return [String] def encoding - encoder.data.map{|a| a.map{|b| b ? '1' : '0' }.join } + width = encoder.width + height = encoder.height + + height.times.map { |y| width.times.map { |x| bit?(x, y) ? '1' : '0' }.join } end - def semacode? - #TODO: Not sure if this is right - data =~ /^http:\/\// + # NOTE: this method is not exposed via the gem so using send ahead of opening a PR to hopefully support: + # + # https://github.com/mtgrosser/dmtx/blob/master/lib/dmtx/data_matrix.rb#L133-L135 + # + # @param x [Integer] x-coordinate + # @param y [Integer] y-coordinate + # @return [Boolean] + def bit?(x, y) + encoder.send(:bit?, x, y) end + # The data being encoded. + # + # @return [String] def to_s data end end end diff --git a/lib/barby/version.rb b/lib/barby/version.rb index 9484c7a..07f5aa8 100644 --- a/lib/barby/version.rb +++ b/lib/barby/version.rb @@ -1,9 +1,9 @@ module Barby #:nodoc: module VERSION #:nodoc: MAJOR = 0 - MINOR = 6 - TINY = 8 + MINOR = 7 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.').freeze end end diff --git a/test/data_matrix_test.rb b/test/data_matrix_test.rb index 6e971b7..aa5a37d 100644 --- a/test/data_matrix_test.rb +++ b/test/data_matrix_test.rb @@ -1,30 +1,40 @@ require 'test_helper' require 'barby/barcode/data_matrix' class DataMatrixTest < Barby::TestCase before do @data = "humbaba" @code = Barby::DataMatrix.new(@data) end it "should have the expected encoding" do - @code.encoding.must_equal ["1010101010101010", "1011111000011111", "1110111000010100", - "1110100100000111", "1101111010101000", "1101111011110011", - "1111111100000100", "1100101111110001", "1001000010001010", - "1101010110111011", "1000000100011110", "1001010010000011", - "1101100111011110", "1110111010000101", "1110010110001010", - "1111111111111111"] + @code.encoding.must_equal [ + "10101010101010", + "10111010000001", + "11100101101100", + "11101001110001", + "11010101111110", + "11100101100001", + "11011001011110", + "10011011010011", + "11011010000100", + "10101100101001", + "11011100001100", + "10101110110111", + "11000001010100", + "11111111111111", + ] end it "should return data on to_s" do @code.to_s.must_equal @data end it "should be able to change its data" do prev_encoding = @code.encoding @code.data = "after eight" @code.encoding.wont_equal prev_encoding end end
toretore/barby
97fee83ee5b8df41686cc92adf05c07918ef8d18
Fix Rmagick deprecation warning
diff --git a/lib/barby/outputter/rmagick_outputter.rb b/lib/barby/outputter/rmagick_outputter.rb index 413501a..a6ca4b4 100644 --- a/lib/barby/outputter/rmagick_outputter.rb +++ b/lib/barby/outputter/rmagick_outputter.rb @@ -1,167 +1,167 @@ require 'barby/outputter' require 'rmagick' module Barby # Renders images from barcodes using RMagick # # Registers the to_png, to_gif, to_jpg and to_image methods # # Options: # # * xdim - # * ydim - 2D only # * height - 1D only # * margin - # * foreground - RMagick "colorspec" # * background - ^ class RmagickOutputter < Outputter register :to_png, :to_gif, :to_jpg, :to_image attr_writer :height, :xdim, :ydim, :margin, :foreground, :background #Returns a string containing a PNG image def to_png(*a) to_blob('png', *a) end #Returns a string containint a GIF image def to_gif(*a) to_blob('gif', *a) end #Returns a string containing a JPEG image def to_jpg(*a) to_blob('jpg', *a) end def to_blob(format, *a) img = to_image(*a) blob = img.to_blob{|i| i.format = format } #Release the memory used by RMagick explicitly. Ruby's GC #isn't aware of it and can't clean it up automatically img.destroy! if img.respond_to?(:destroy!) blob end #Returns an instance of Magick::Image def to_image(opts={}) with_options opts do b = background #Capture locally because Magick::Image.new block uses instance_eval - canvas = Magick::Image.new(full_width, full_height){ self.background_color = b } + canvas = Magick::Image.new(full_width, full_height){ |i| i.background_color = b } bars = Magick::Draw.new bars.fill = foreground x1 = margin y1 = margin if barcode.two_dimensional? encoding.each do |line| line.split(//).map{|c| c == '1' }.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(ydim-1) # For single pixels use point if x1 == x2 && y1 == y2 bars.point(x1,y1) else # For single pixel lines, use line if x1 == x2 bars.line(x1, y1, x1, y2) elsif y1 == y2 bars.line(x1, y1, x2, y1) else bars.rectangle(x1, y1, x2, y2) end end end x1 += xdim end x1 = margin y1 += ydim end else booleans.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(height-1) # For single pixel width, use line if x1 == x2 bars.line(x1, y1, x1, y2) else bars.rectangle(x1, y1, x2, y2) end end x1 += xdim end end bars.draw(canvas) canvas end end #The height of the barcode in px #For 2D barcodes this is the number of "lines" * ydim def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end #The width of the barcode in px def width length * xdim end #Number of modules (xdims) on the x axis def length barcode.two_dimensional? ? encoding.first.length : encoding.length end #X dimension. 1X == 1px def xdim @xdim || 1 end #Y dimension. Only for 2D codes def ydim @ydim || xdim end #The margin of each edge surrounding the barcode in pixels def margin @margin || 10 end #The full width of the image. This is the width of the #barcode + the left and right margin def full_width width + (margin * 2) end #The height of the image. This is the height of the #barcode + the top and bottom margin def full_height height + (margin * 2) end def foreground @foreground || 'black' end def background @background || 'white' end end end
toretore/barby
e3cae50c8c29bd77fb9a9722afb6b9bde93820e9
Add color options to outputters
diff --git a/lib/barby/barcode.rb b/lib/barby/barcode.rb index 5bf9efa..ba4c079 100644 --- a/lib/barby/barcode.rb +++ b/lib/barby/barcode.rb @@ -1,116 +1,116 @@ module Barby #The base class for all barcodes. It includes some method_missing magic #that is used to find registered outputters. # #The only interface requirement of a barcode class is that is has an encoding #method that returns a string consisting of 1s and 0s representing the barcode's #"black" and "white" parts. One digit is the width of the "X dimension"; that is, #"101100" represents a single-width bar followed by a single-width space, then #a bar and a space twice that width. # #Example implementation: # # class StaticBarcode < Barby::Barcode1D # def encoding # '101100111000111100001' # end # end - # + # # require 'barby/outputter/ascii_outputter' # puts StaticBarcode.new.to_ascii(:height => 3) # # # ## ### #### # # # ## ### #### # # # ## ### #### # # #2D implementation: # # class Static2DBarcode < Barby::Barcode2D # def encoding # ['1010101', '010101110', '0001010100'] # end # end class Barcode - - + + #Every barcode must have an encoding method. This method returns #a string containing a series of 1 and 0, representing bars and #spaces. One digit is the width of one "module" or X dimension. # #If the barcode is 2D, it returns an array of strings representing #each line in the barcode def encoding raise NotImplementedError, 'Every barcode should implement this method' end #Is this barcode valid? def valid? false end def to_s self.class.name.split('::').last end #Is this barcode 2D? def two_dimensional? is_a? Barcode2D end def method_missing(name, *args, &b)#:nodoc: #See if an outputter has registered this method if self.class.outputters.include?(name) klass, method_name = self.class.outputters[name] klass.new(self).send(method_name, *args, &b) else super end end #Returns an instantiated outputter for +name+ if any outputter #has registered that name def outputter_for(name, *a, &b) outputter_class_for(name).new(self, *a, &b) end #Get the outputter class object for +name+ def outputter_class_for(name) self.class.outputters[name].first end class << self def outputters @@outputters ||= {} end #Registers an outputter with +name+ so that a call to #+name+ on a Barcode instance will be delegated to this outputter def register_outputter(name, klass, method_name) outputters[name] = [klass, method_name] end end end #Most barcodes are one-dimensional. They have bars. class Barcode1D < Barcode end #2D barcodes are 1D barcodes stacked on top of each other. #Their encoding method must return an array of strings class Barcode2D < Barcode end end diff --git a/lib/barby/outputter.rb b/lib/barby/outputter.rb index ae1a6ea..6ca7274 100644 --- a/lib/barby/outputter.rb +++ b/lib/barby/outputter.rb @@ -1,135 +1,135 @@ require 'barby/barcode' module Barby #An Outputter creates something from a barcode. That something can be #anything, but is most likely a graphical representation of the barcode. #Outputters can register methods on barcodes that will be associated with #them. # #The basic structure of an outputter class: # # class FooOutputter < Barby::Outputter # register :to_foo # def to_too # do_something_with(barcode.encoding) # end # end # #Barcode#to_foo will now be available to all barcodes class Outputter attr_accessor :barcode #An outputter instance will have access to a Barcode def initialize(barcode) self.barcode = barcode end - + #Register one or more handler methods with this outputter #Barcodes will then be able to use these methods to get the output #from the outputter. For example, if you have an ImageOutputter, #you could do: # #register :to_png, :to_gif # #You could then do aBarcode.to_png and get the result of that method. #The class which registers the method will receive the barcode as the only #argument, and the default implementation of initialize puts that into #the +barcode+ accessor. # #You can also have different method names on the barcode and the outputter #by providing a hash: # #register :to_png => :create_png, :to_gif => :create_gif def self.register(*method_names) if method_names.first.is_a? Hash method_names.first.each do |name, method_name| Barcode.register_outputter(name, self, method_name) end else method_names.each do |name| Barcode.register_outputter(name, self, name) end end end def two_dimensional? barcode.respond_to?(:two_dimensional?) && barcode.two_dimensional? end #Converts the barcode's encoding (a string containing 1s and 0s) #to true and false values (1 == true == "black bar") # #If the barcode is 2D, each line will be converted to an array #in the same way def booleans(reload=false)#:doc: if two_dimensional? encoding(reload).map{|l| l.split(//).map{|c| c == '1' } } else encoding(reload).split(//).map{|c| c == '1' } end end #Returns the barcode's encoding. The encoding #is cached and can be reloaded by passing true def encoding(reload=false)#:doc: @encoding = barcode.encoding if reload @encoding ||= barcode.encoding end #Collects continuous groups of bars and spaces (1 and 0) #into arrays where the first item is true or false (1 or 0) #and the second is the size of the group # #For example, "1100111000" becomes [[true,2],[false,2],[true,3],[false,3]] def boolean_groups(reload=false) if two_dimensional? encoding(reload).map do |line| line.scan(/1+|0+/).map do |group| [group[0,1] == '1', group.size] end end else encoding(reload).scan(/1+|0+/).map do |group| [group[0,1] == '1', group.size] end end end private #Takes a hash and temporarily sets properties on self (the outputter object) #corresponding with the keys to their values. When the block exits, the #properties are reset to their original values. Returns whatever the block returns. def with_options(options={}) original_options = options.inject({}) do |origs,pair| if respond_to?(pair.first) && respond_to?("#{pair.first}=") origs[pair.first] = send(pair.first) send("#{pair.first}=", pair.last) end origs end rv = yield original_options.each do |attribute,value| send("#{attribute}=", value) end rv end end end diff --git a/lib/barby/outputter/cairo_outputter.rb b/lib/barby/outputter/cairo_outputter.rb index 2434100..4190bb8 100644 --- a/lib/barby/outputter/cairo_outputter.rb +++ b/lib/barby/outputter/cairo_outputter.rb @@ -1,190 +1,198 @@ require 'barby/outputter' require 'cairo' require 'stringio' module Barby - #Uses Cairo to render a barcode to a number of formats: PNG, PS, EPS, PDF and SVG + # Uses Cairo to render a barcode to a number of formats: PNG, PS, EPS, PDF and SVG # - #Registers methods render_to_cairo_context, to_png, to_ps, to_eps, to_pdf and to_svg + # Registers methods render_to_cairo_context, to_png, to_ps, to_eps, to_pdf and to_svg + # + # Options: + # + # * xdim + # * ydim - (2D only) + # * height - (1D only) + # * foreground - Cairo::Color::Base or Cairo::Color.parse(value) + # * background - ^ class CairoOutputter < Outputter register :render_to_cairo_context register :to_png if Cairo.const_defined?(:PSSurface) register :to_ps register :to_eps if Cairo::PSSurface.method_defined?(:eps=) end register :to_pdf if Cairo.const_defined?(:PDFSurface) register :to_svg if Cairo.const_defined?(:SVGSurface) attr_writer :x, :y, :xdim, :height, :margin def initialize(*) super @x, @y, @xdim, @height, @margin = nil end #Render the barcode onto a Cairo context def render_to_cairo_context(context, options={}) if context.respond_to?(:have_current_point?) and context.have_current_point? current_x, current_y = context.current_point else current_x = x(options) || margin(options) current_y = y(options) || margin(options) end _xdim = xdim(options) _height = height(options) original_current_x = current_x context.save do - context.set_source_color(:black) + context.set_source_color(options[:foreground] || :black) context.fill do if barcode.two_dimensional? boolean_groups.each do |groups| groups.each do |bar,amount| current_width = _xdim * amount if bar context.rectangle(current_x, current_y, current_width, _xdim) end current_x += current_width end current_x = original_current_x current_y += _xdim end else boolean_groups.each do |bar,amount| current_width = _xdim * amount if bar context.rectangle(current_x, current_y, current_width, _height) end current_x += current_width end end end end context end #Render the barcode to a PNG image def to_png(options={}) output_to_string_io do |io| Cairo::ImageSurface.new(options[:format], full_width(options), full_height(options)) do |surface| render(surface, options) surface.write_to_png(io) end end end #Render the barcode to a PS document def to_ps(options={}) output_to_string_io do |io| Cairo::PSSurface.new(io, full_width(options), full_height(options)) do |surface| surface.eps = options[:eps] if surface.respond_to?(:eps=) render(surface, options) end end end #Render the barcode to an EPS document def to_eps(options={}) to_ps(options.merge(:eps => true)) end #Render the barcode to a PDF document def to_pdf(options={}) output_to_string_io do |io| Cairo::PDFSurface.new(io, full_width(options), full_height(options)) do |surface| render(surface, options) end end end #Render the barcode to an SVG document def to_svg(options={}) output_to_string_io do |io| Cairo::SVGSurface.new(io, full_width(options), full_height(options)) do |surface| render(surface, options) end end end def x(options={}) @x || options[:x] end def y(options={}) @y || options[:y] end def width(options={}) (barcode.two_dimensional? ? encoding.first.length : encoding.length) * xdim(options) end def height(options={}) if barcode.two_dimensional? encoding.size * xdim(options) else @height || options[:height] || 50 end end def full_width(options={}) width(options) + (margin(options) * 2) end def full_height(options={}) height(options) + (margin(options) * 2) end def xdim(options={}) @xdim || options[:xdim] || 1 end def margin(options={}) @margin || options[:margin] || 10 end private def output_to_string_io io = StringIO.new yield(io) io.rewind io.read end def render(surface, options) context = Cairo::Context.new(surface) yield(context) if block_given? context.set_source_color(options[:background] || :white) context.paint render_to_cairo_context(context, options) context end end end diff --git a/lib/barby/outputter/png_outputter.rb b/lib/barby/outputter/png_outputter.rb index 5d263a1..bc0b8c6 100644 --- a/lib/barby/outputter/png_outputter.rb +++ b/lib/barby/outputter/png_outputter.rb @@ -1,111 +1,143 @@ require 'barby/outputter' require 'chunky_png' module Barby - #Renders the barcode to a PNG image using chunky_png (gem install chunky_png) + # Renders the barcode to a PNG image using chunky_png (gem install chunky_png) + # + # Registers the to_png, to_datastream and to_canvas methods + # + # Options: + # + # * xdim: X dimension - bar width [1] + # * ydim: Y dimension - bar height (2D only) [1] + # * height: Height of bars (1D only) [100] + # * margin: Size of margin around barcode [0] + # * foreground: Foreground color (see ChunkyPNG::Color - can be HTML color name) [black] + # * background: Background color (see ChunkyPNG::Color - can be HTML color name) [white] # - #Registers the to_png, to_datastream and to_canvas methods class PngOutputter < Outputter register :to_png, :to_image, :to_datastream - attr_writer :xdim, :ydim, :width, :height, :margin + attr_writer :xdim, :ydim, :height, :margin - def initialize(*) - super - @xdim, @height, @margin = nil - end - #Creates a PNG::Canvas object and renders the barcode on it + #Creates a ChunkyPNG::Image object and renders the barcode on it def to_image(opts={}) with_options opts do - canvas = ChunkyPNG::Image.new(full_width, full_height, ChunkyPNG::Color::WHITE) + canvas = ChunkyPNG::Image.new(full_width, full_height, background) if barcode.two_dimensional? x, y = margin, margin booleans.each do |line| line.each do |bar| if bar x.upto(x+(xdim-1)) do |xx| y.upto y+(ydim-1) do |yy| - canvas[xx,yy] = ChunkyPNG::Color::BLACK + canvas[xx,yy] = foreground end end end x += xdim end y += ydim x = margin end else x, y = margin, margin booleans.each do |bar| if bar x.upto(x+(xdim-1)) do |xx| y.upto y+(height-1) do |yy| - canvas[xx,yy] = ChunkyPNG::Color::BLACK + canvas[xx,yy] = foreground end end end x += xdim end end canvas end end #Create a ChunkyPNG::Datastream containing the barcode image # # :constraints - Value is passed on to ChunkyPNG::Image#to_datastream # E.g. to_datastream(:constraints => {:color_mode => ChunkyPNG::COLOR_GRAYSCALE}) def to_datastream(*a) constraints = a.first && a.first[:constraints] ? [a.first[:constraints]] : [] to_image(*a).to_datastream(*constraints) end #Renders the barcode to a PNG image def to_png(*a) to_datastream(*a).to_s end def width length * xdim end def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end def full_width width + (margin * 2) end def full_height height + (margin * 2) end def xdim @xdim || 1 end def ydim @ydim || xdim end def margin @margin || 10 end + + def background=(c) + @background = if c.is_a?(String) || c.is_a?(Symbol) + ChunkyPNG::Color.html_color(c.to_sym) + else + c + end + end + + def background + @background || ChunkyPNG::Color::WHITE + end + + def foreground=(c) + @foreground = if c.is_a?(String) || c.is_a?(Symbol) + ChunkyPNG::Color.html_color(c.to_sym) + else + c + end + end + + def foreground + @foreground || ChunkyPNG::Color::BLACK + end + + def length barcode.two_dimensional? ? encoding.first.length : encoding.length end end end diff --git a/lib/barby/outputter/prawn_outputter.rb b/lib/barby/outputter/prawn_outputter.rb index 00ce804..382835f 100644 --- a/lib/barby/outputter/prawn_outputter.rb +++ b/lib/barby/outputter/prawn_outputter.rb @@ -1,126 +1,129 @@ require 'barby/outputter' require 'prawn' module Barby class PrawnOutputter < Outputter register :to_pdf, :annotate_pdf - attr_writer :xdim, :ydim, :x, :y, :height, :margin, :unbleed - - - def initialize(*) - super - @xdim, @ydim, @x, @y, @height, @margin, @unbleed = nil - end + attr_writer :xdim, :ydim, :x, :y, :height, :margin, :unbleed, :color def to_pdf(opts={}) doc_opts = opts.delete(:document) || {} doc_opts[:page_size] ||= 'A4' annotate_pdf(Prawn::Document.new(doc_opts), opts).render end def annotate_pdf(pdf, opts={}) with_options opts do xpos, ypos = x, y orig_xpos = xpos + orig_color = pdf.fill_color + + pdf.fill_color = color if color if barcode.two_dimensional? boolean_groups.reverse_each do |groups| groups.each do |bar,amount| if bar pdf.move_to(xpos+unbleed, ypos+unbleed) pdf.line_to(xpos+unbleed, ypos+ydim-unbleed) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+ydim-unbleed) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+unbleed) pdf.line_to(xpos+unbleed, ypos+unbleed) pdf.fill end xpos += (xdim*amount) end xpos = orig_xpos ypos += ydim end else boolean_groups.each do |bar,amount| if bar pdf.move_to(xpos+unbleed, ypos) pdf.line_to(xpos+unbleed, ypos+height) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+height) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos) pdf.line_to(xpos+unbleed, ypos) pdf.fill end xpos += (xdim*amount) end - end + end#if - end + pdf.fill_color = orig_color + + end#with_options pdf end def length two_dimensional? ? encoding.first.length : encoding.length end def width length * xdim end def height two_dimensional? ? (ydim * encoding.length) : (@height || 50) end def full_width width + (margin * 2) end def full_height height + (margin * 2) end #Margin is used for x and y if not given explicitly, effectively placing the barcode #<margin> points from the [left,bottom] of the page. #If you define x and y, there will be no margin. And if you don't define margin, it's 0. def margin @margin || 0 end def x @x || margin end def y @y || margin end def xdim @xdim || 1 end def ydim @ydim || xdim end #Defines an amount to reduce black bars/squares by to account for "ink bleed" #If xdim = 3, unbleed = 0.2, a single/width black bar will be 2.6 wide #For 2D, both x and y dimensions are reduced. def unbleed @unbleed || 0 end + def color + @color + end + private def page_size(xdim, height, margin) [width(xdim,margin), height(height,margin)] end end end diff --git a/lib/barby/outputter/rmagick_outputter.rb b/lib/barby/outputter/rmagick_outputter.rb index e6fa9e4..413501a 100644 --- a/lib/barby/outputter/rmagick_outputter.rb +++ b/lib/barby/outputter/rmagick_outputter.rb @@ -1,152 +1,167 @@ require 'barby/outputter' require 'rmagick' module Barby - #Renders images from barcodes using RMagick + # Renders images from barcodes using RMagick # - #Registers the to_png, to_gif, to_jpg and to_image methods + # Registers the to_png, to_gif, to_jpg and to_image methods + # + # Options: + # + # * xdim - + # * ydim - 2D only + # * height - 1D only + # * margin - + # * foreground - RMagick "colorspec" + # * background - ^ class RmagickOutputter < Outputter register :to_png, :to_gif, :to_jpg, :to_image - attr_writer :height, :xdim, :ydim, :margin + attr_writer :height, :xdim, :ydim, :margin, :foreground, :background - def initialize(*) - super - @height, @xdim, @ydim, @margin = nil - end - #Returns a string containing a PNG image def to_png(*a) to_blob('png', *a) end #Returns a string containint a GIF image def to_gif(*a) to_blob('gif', *a) end #Returns a string containing a JPEG image def to_jpg(*a) to_blob('jpg', *a) end def to_blob(format, *a) img = to_image(*a) blob = img.to_blob{|i| i.format = format } #Release the memory used by RMagick explicitly. Ruby's GC #isn't aware of it and can't clean it up automatically img.destroy! if img.respond_to?(:destroy!) blob end #Returns an instance of Magick::Image def to_image(opts={}) with_options opts do - canvas = Magick::Image.new(full_width, full_height) + b = background #Capture locally because Magick::Image.new block uses instance_eval + canvas = Magick::Image.new(full_width, full_height){ self.background_color = b } bars = Magick::Draw.new + bars.fill = foreground x1 = margin y1 = margin if barcode.two_dimensional? encoding.each do |line| line.split(//).map{|c| c == '1' }.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(ydim-1) # For single pixels use point if x1 == x2 && y1 == y2 bars.point(x1,y1) else # For single pixel lines, use line if x1 == x2 bars.line(x1, y1, x1, y2) elsif y1 == y2 bars.line(x1, y1, x2, y1) else bars.rectangle(x1, y1, x2, y2) end end end x1 += xdim end x1 = margin y1 += ydim end else booleans.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(height-1) # For single pixel width, use line if x1 == x2 bars.line(x1, y1, x1, y2) else bars.rectangle(x1, y1, x2, y2) end end x1 += xdim end end bars.draw(canvas) canvas end end #The height of the barcode in px #For 2D barcodes this is the number of "lines" * ydim def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end #The width of the barcode in px def width length * xdim end #Number of modules (xdims) on the x axis def length barcode.two_dimensional? ? encoding.first.length : encoding.length end #X dimension. 1X == 1px def xdim @xdim || 1 end #Y dimension. Only for 2D codes def ydim @ydim || xdim end #The margin of each edge surrounding the barcode in pixels def margin @margin || 10 end #The full width of the image. This is the width of the #barcode + the left and right margin def full_width width + (margin * 2) end #The height of the image. This is the height of the #barcode + the top and bottom margin def full_height height + (margin * 2) end + def foreground + @foreground || 'black' + end + + def background + @background || 'white' + end + + end end diff --git a/lib/barby/outputter/svg_outputter.rb b/lib/barby/outputter/svg_outputter.rb index 0987082..eb6df61 100644 --- a/lib/barby/outputter/svg_outputter.rb +++ b/lib/barby/outputter/svg_outputter.rb @@ -1,219 +1,223 @@ require 'barby/outputter' module Barby #Renders the barcode to a simple SVG image using pure ruby # #Registers the to_svg, bars_to_path, and bars_to_rects method # #Bars can be rendered as a stroked path or as filled rectangles. Path #generally yields smaller files, but this doesn't render cleanly in Firefox #3 for odd xdims. My guess is that the renderer tries to put half a pixel #on one side of the path and half on the other, leading to fuzzy dithering #instead of sharp, clean b&w. # #Therefore, default behavior is to use a path for even xdims, and #rectangles for odd. This can be overridden by calling with explicit #:use => 'rects' or :use => 'path' options. class SvgOutputter < Outputter register :to_svg, :bars_to_rects, :bars_to_path - attr_writer :title, :xdim, :ydim, :height, :rmargin, :lmargin, :tmargin, :bmargin, :xmargin, :ymargin, :margin + attr_writer :title, :xdim, :ydim, :height, :rmargin, :lmargin, :tmargin, :bmargin, :xmargin, :ymargin, :margin, :foreground, :background - def initialize(*) - super - @title, @xdim, @ydim, @height, @rmargin, @lmargin, @tmargin, @bmargin, @xmargin, @ymargin, @margin = nil - end def to_svg(opts={}) with_options opts do case opts[:use] when 'rects' then bars = bars_to_rects when 'path' then bars = bars_to_path else xdim_odd = (xdim % 2 == 1) bars = xdim_odd ? bars_to_rects : bars_to_path end <<-"EOT" <?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="#{svg_width(opts)}px" height="#{svg_height(opts)}px" viewBox="0 0 #{svg_width(opts)} #{svg_height(opts)}" version="1.1" preserveAspectRatio="none" > <title>#{escape title}</title> <g id="canvas" #{transform(opts)}> -<rect x="0" y="0" width="#{full_width}px" height="#{full_height}px" fill="white" /> -<g id="barcode" fill="black"> +<rect x="0" y="0" width="#{full_width}px" height="#{full_height}px" fill="#{background}" /> +<g id="barcode" fill="#{foreground}"> #{bars} </g></g> </svg> EOT end end def bars_to_rects(opts={}) rects = '' with_options opts do x, y = lmargin, tmargin if barcode.two_dimensional? boolean_groups.each do |line| line.each do |bar, amount| bar_width = xdim * amount if bar rects << %Q|<rect x="#{x}" y="#{y}" width="#{bar_width}px" height="#{ydim}px" />\n| end x += bar_width end y += ydim x = lmargin end else boolean_groups.each do |bar, amount| bar_width = xdim * amount if bar rects << %Q|<rect x="#{x}" y="#{y}" width="#{bar_width}px" height="#{height}px" />\n| end x += bar_width end end end # with_options rects end def bars_to_path(opts={}) with_options opts do %Q|<path stroke="black" stroke-width="#{xdim}" d="#{bars_to_path_data(opts)}" />| end end def bars_to_path_data(opts={}) path_data = '' with_options opts do x, y = lmargin+(xdim/2), tmargin if barcode.two_dimensional? booleans.each do |line| line.each do |bar| if bar path_data << "M#{x} #{y}V #{y+ydim}" end x += xdim end y += ydim x = lmargin+(xdim/2) end else booleans.each do |bar| if bar path_data << "M#{x} #{y}V#{y+height}" end x += xdim end end end # with_options path_data end def title @title || barcode.to_s end def width length * xdim end def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end def full_width width + lmargin + rmargin end def full_height height + tmargin + bmargin end def xdim @xdim || 1 end def ydim @ydim || xdim end def lmargin @lmargin || _xmargin end def rmargin @rmargin || _xmargin end def tmargin @tmargin || _ymargin end def bmargin @bmargin || _ymargin end def xmargin return nil if @lmargin || @rmargin _margin end def ymargin return nil if @tmargin || @bmargin _margin end def margin return nil if @ymargin || @xmargin || @tmargin || @bmargin || @lmargin || @rmargin _margin end def length barcode.two_dimensional? ? encoding.first.length : encoding.length end + def foreground + @foreground || '#000' + end + + def background + @background || '#fff' + end + def svg_width(opts={}) opts[:rot] ? full_height : full_width end def svg_height(opts={}) opts[:rot] ? full_width : full_height end def transform(opts={}) opts[:rot] ? %Q|transform="rotate(-90) translate(-#{full_width}, 0)"| : nil end private def _xmargin @xmargin || _margin end def _ymargin @ymargin || _margin end def _margin @margin || 10 end #Escape XML special characters <, & and > def escape(str) str.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;') end end end
toretore/barby
1d11e801910990daa4b778aa8176f885077c743c
RMagick outputter should use line command for lines
diff --git a/lib/barby/outputter/rmagick_outputter.rb b/lib/barby/outputter/rmagick_outputter.rb index 5f6bded..e6fa9e4 100644 --- a/lib/barby/outputter/rmagick_outputter.rb +++ b/lib/barby/outputter/rmagick_outputter.rb @@ -1,140 +1,152 @@ require 'barby/outputter' require 'rmagick' module Barby #Renders images from barcodes using RMagick # #Registers the to_png, to_gif, to_jpg and to_image methods class RmagickOutputter < Outputter register :to_png, :to_gif, :to_jpg, :to_image attr_writer :height, :xdim, :ydim, :margin def initialize(*) super @height, @xdim, @ydim, @margin = nil end #Returns a string containing a PNG image def to_png(*a) to_blob('png', *a) end #Returns a string containint a GIF image def to_gif(*a) to_blob('gif', *a) end #Returns a string containing a JPEG image def to_jpg(*a) to_blob('jpg', *a) end def to_blob(format, *a) img = to_image(*a) blob = img.to_blob{|i| i.format = format } #Release the memory used by RMagick explicitly. Ruby's GC #isn't aware of it and can't clean it up automatically img.destroy! if img.respond_to?(:destroy!) blob end #Returns an instance of Magick::Image def to_image(opts={}) with_options opts do canvas = Magick::Image.new(full_width, full_height) bars = Magick::Draw.new x1 = margin y1 = margin if barcode.two_dimensional? encoding.each do |line| line.split(//).map{|c| c == '1' }.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(ydim-1) # For single pixels use point if x1 == x2 && y1 == y2 bars.point(x1,y1) else - bars.rectangle(x1, y1, x2, y2) + # For single pixel lines, use line + if x1 == x2 + bars.line(x1, y1, x1, y2) + elsif y1 == y2 + bars.line(x1, y1, x2, y1) + else + bars.rectangle(x1, y1, x2, y2) + end end end x1 += xdim end x1 = margin y1 += ydim end else booleans.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(height-1) - bars.rectangle(x1, y1, x2, y2) + # For single pixel width, use line + if x1 == x2 + bars.line(x1, y1, x1, y2) + else + bars.rectangle(x1, y1, x2, y2) + end end x1 += xdim end end bars.draw(canvas) canvas end end #The height of the barcode in px #For 2D barcodes this is the number of "lines" * ydim def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end #The width of the barcode in px def width length * xdim end #Number of modules (xdims) on the x axis def length barcode.two_dimensional? ? encoding.first.length : encoding.length end #X dimension. 1X == 1px def xdim @xdim || 1 end #Y dimension. Only for 2D codes def ydim @ydim || xdim end #The margin of each edge surrounding the barcode in pixels def margin @margin || 10 end #The full width of the image. This is the width of the #barcode + the left and right margin def full_width width + (margin * 2) end #The height of the image. This is the height of the #barcode + the top and bottom margin def full_height height + (margin * 2) end end end
toretore/barby
51b642b49be9b4067131935987f01911bcb5aa38
Use freeze
diff --git a/lib/barby/version.rb b/lib/barby/version.rb index 7206ffb..45dcfb7 100644 --- a/lib/barby/version.rb +++ b/lib/barby/version.rb @@ -1,9 +1,9 @@ module Barby #:nodoc: module VERSION #:nodoc: MAJOR = 0 MINOR = 6 TINY = 6 - STRING = [MAJOR, MINOR, TINY].join('.') + STRING = [MAJOR, MINOR, TINY].join('.').freeze end end