Guest User

Untitled

a guest
Jun 23rd, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. ## all_diff will calculate some cumulative fields and save them back to the db
  2.  
  3. ## Model
  4. class Reading < ActiveRecord::Base
  5.  
  6. def self.all_diff(unit_id)
  7. first = find(:first, :conditions => ["unit_id = ?", unit_id], :order => "date asc" )
  8. counter_last = first.counter
  9. date_last = first.date
  10.  
  11. find(:all, :conditions => ["unit_id = ?", unit_id], :order => "date asc" ).each do |r|
  12. r.diff_days = r.date - date_last
  13.  
  14. # analog meters will reset to 0000 when after reaching 9999. Difficult to recognise automatically, but will try
  15. if r.counter < counter_last and r.counter < 9000 and counter_last >9000:
  16. r.diff_counter = r.counter+ 10000- counter_last
  17. elsif
  18. r.diff_counter = r.counter - counter_last
  19. end
  20.  
  21. if r.type == "ElectricityReading"
  22. co2_factor = 0.43
  23. elsif r.type == "GasReading"
  24. co2_factor = 2.28
  25. elsif r.type == "WaterReading"
  26. co2_factor = 5
  27. else
  28. co2_factor = nil
  29. end
  30.  
  31. r.diff_co2 = r.diff_counter.to_f * co2_factor
  32. #if this is the first record, the denominator will be zero, so we'll skip it
  33. unless r.diff_days == 0
  34. r.diff_counter_days = r.diff_counter.to_f / r.diff_days.to_f
  35. r.diff_co2_days = r.diff_counter_days * co2_factor
  36. end
  37. logger.debug r.type
  38. r.save
  39. counter_last = r.counter
  40. date_last =r.date
  41.  
  42. end
  43.  
  44. end
  45.  
  46.  
  47. ## Sub Class
  48. class ElectricityReading < Reading
  49.  
  50.  
  51. ## Controller
  52. def create_electricity_reading
  53. @reading = ElectricityReading.new(params[:reading])
  54. respond_to do |format|
  55. if @reading.save
  56. flash[:notice] = "created E-reading ok"
  57. format.html { redirect_to :action =>"index" }
  58. else
  59. format.html { render :action => "new" }
  60. end
  61. end
  62. ElectricityReading.all_diff(params[:reading][:unit_id])
  63. end
Add Comment
Please, Sign In to add comment