Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## models/Interpolate.rb
- #Class to store interpolated data derived fro readings
- class Interpolation < ActiveRecord::Base
- # holds readings that should be interpolated
- attr_reader :readings
- attr_reader :rdates
- attr_reader :rdiff_counter_days
- attr_reader :rdiff_co2_days
- rec = nil
- # Class to calculate interpolation for each day
- def self.calc(unit_id, type)
- #get all readings
- @readings = Reading.find_all_by_unit_id_and_type(unit_id,type, :select => "date, diff_counter_days, diff_co2_days", :order => "date asc")
- #init arrays
- @rdates = []
- @rdiff_counter_days = []
- @rdiff_co2_days = []
- #send readings to arrays
- @readings.each do |r|
- @rdates << r.date
- @rdiff_counter_days << r.diff_counter_days
- @rdiff_co2_days << r.diff_co2_days
- end
- #iterate down through each day in the period
- day = @rdates.last
- diff_counter_days = @rdiff_counter_days.last
- diff_co2_days = @rdiff_co2_days
- while day>=@rdates.first do
- #check if day has reading
- if i=@rdates.rindex(day)
- print "match! : "
- # set interpolated fields with matched data
- diff_counter_days = @rdiff_counter_days[i]
- diff_co2_days = @rdiff_co2_days[i]
- end
- # debug output
- print day
- print ": "
- print diff_counter_days
- print ", "
- print diff_co2_days
- print "\n"
- # check update if exist or create new if not
- rec = Interpolation.find(:first, :conditions => ["unit_id = ? and date = ? and type = ?", unit_id, day, type] )
- if rec
- rec.update_attributes(:diff_counter_days => diff_counter_days, :diff_co2_days => diff_co2_days )
- puts "update"
- else
- puts "create"
- rec = Interpolation.new(:type => type, :date => day, :diff_counter_days => diff_counter_days, :diff_co2_days => diff_co2_days )
- rec.save
- end
- # decrease day by one
- day=day.yesterday
- end
- end
- end
- ## somehow updates use the wrong class. They update Reading and not Interpolate
- Loading development environment (Rails 2.3.2)
- >> rec = Interpolation.find(:first, :conditions => ["unit_id = ? and date = ? and type = ?", 1, "2009-05-07", "ElectricityReading"] )
- => #<ElectricityReading id: 1, unit_id: 1, type: "ElectricityReading", date: "2009-05-07", created_at: nil, updated_at: nil, diff_counter_days: #<BigDecimal:18a6adc,'0.123E3',4(8)>, diff_co2_days: #<BigDecimal:18a69d8,'0.234E3',4(8)>>
- >> rec.diff_counter_days =0
- => 0
- >> rec.save!
- => true
- >> rec = Interpolation.find(:first, :conditions => ["unit_id = ? and date = ? and type = ?", 1, "2009-05-07", "ElectricityReading"] )
- => #<ElectricityReading id: 1, unit_id: 1, type: "ElectricityReading", date: "2009-05-07", created_at: nil, updated_at: nil, diff_counter_days: #<BigDecimal:183ebbc,'0.123E3',4(8)>, diff_co2_days: #<BigDecimal:183e9f0,'0.234E3',4(8)>>
Add Comment
Please, Sign In to add comment