开发者

rails data aggregation

开发者 https://www.devze.com 2022-12-30 11:33 出处:网络
I have to create a hash of the f开发者_如何学Goorm h[:bill] => [\"Billy\", \"NA\", 20, \"PROJ_A\"] by login where 20 is the cumulative number of hours reported by the login for all task transactions r

I have to create a hash of the f开发者_如何学Goorm h[:bill] => ["Billy", "NA", 20, "PROJ_A"] by login where 20 is the cumulative number of hours reported by the login for all task transactions returned by the query where each login has multiple reported transactions. Did I do this in a bad way or this seems alright.

h = Hash.new
Task.find_each(:include => [:user], :joins => :user, :conditions => ["from_date >= ? AND from_date <= ? AND category = ?", Date.today - 30, Date.today + 30, 'PROJ1']) do |t|

   h[t.login.intern] = [t.user.name, 'NA', h[t.login.intern].nil? ? (t.hrs_per_day * t.num_days) : h[t.login.intern][2] + (t.hrs_day * t.workdays), t.category]

end

Also if I have to aggregate this data not just by login but login and category how do I accomplish this?

thanks, ash


I would make this

h[:bill] => ["Billy", "NA", 20, "PROJ_A"]

a hash like so

{ :user => t.user.name, :your_key_name => 'NA', :cumulative_hours => 20, :category => 'PROJ_A' }

so the values are accessible with keys instead of element indexes which becomes a bit hard to see when you are not iterating through a array

To access the data by user and category you can do some thing like this

user_hash = {}

Task.find_each(:include => [:user], :joins => :user, :conditions => ["from_date >= ? AND from_date <= ? AND category = ?", Date.today - 30, Date.today + 30, 'PROJ1']) do |task|

  user_hash[task.login.intern] ||= {}
  user_hash[task.login.intern][task.category] = { :user => task.user.name, :your_key_name => 'NA', :cumulative_hours => cumulative_hours(user_hash, task), :category => task.category }

end


def cumulative_hours(user_hash, task)
  if user_hash[task.login.intern] && user_hash[task.login.intern][task.category]
    return user_hash[task.login.intern][task.category][:cumulative_hours] + (task.hrs_day * task.workdays)
  else
    return task.hrs_per_day * task.num_days
  end
 end

For readability reasons I have added meaningful variable names and also created a method to calculate cumulative_hours to keep the code clear, separate code concern and to follow Single Responsibility Principle.

0

精彩评论

暂无评论...
验证码 换一张
取 消