Skip to content

Instantly share code, notes, and snippets.

@josephrexme
Created January 4, 2015 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephrexme/fe445701513a186bb43f to your computer and use it in GitHub Desktop.
Save josephrexme/fe445701513a186bb43f to your computer and use it in GitHub Desktop.
Attendance Logic
=begin
Help with Logic
=end
allRecords = Attendance.pluck(:date, :presence).map { |attendance, presence| [attendance.strftime('%B'), presence] } #=> [['November',true],['November',false],['November',true],['December', true], ['December', false], ['January',false], ['January',true]]
monthFilter = allRecords.uniq.map { |month| [month[0]] } #=> ['November','November', 'November', 'December', 'December', 'January','January']
months = monthFilter.uniq #=> ['November','December','January']
# Expected To do the following:
# To fetch all the records and count the number of true presence with false presence per month. Then get a percentage of true / total in each month
@ccuadrado
Copy link

Try creating a hash of each month, i.e

months = Hash.new()
months.default=[]
allRecords = Attendance.pluck(:date, :presence).map { |attendance, presence| [attendance.strftime('%B'), presence] } #=> [['November',true],['November',false],['November',true],['December', true], ['December', false], ['January',false], ['January',true]]

Collate the records per month.

allRecords.each.map |record|
months[record[0]].push(record)
end

then make a function that takes each key of months and returns a value based on percentaging the array with whatever your business rules are.

@havenwood
Copy link

all_records.group_by(&:first).map { |k, v| trues, falses = v.partition(&:last); [k, "#{falses.size * 100  / trues.size}%"] }
#=> [["November", "50%"], ["December", "100%"], ["January", "100%"]]

@josephrexme
Copy link
Author

Adjusted the code to this:

all_records = Attendance.pluck(:date, :presence).map { |attendance, presence| [attendance.strftime('%B'), presence] } #=> [['November',true],['November',false],['November',true],['December', true], ['December', false], ['January',false], ['January',true]]
    @attendances = all_records.group_by(&:first).map { |k, v| trues, falses = v.partition(&:last); [k, "#{falses.size * 100  / trues.size}%"] } #=> [["November", "0%"], ["December", "0%"], ["January", "0%"]]

But now get 0% on all

@josephrexme
Copy link
Author

In the end, I realized it was the percentage logic that needed to be corrected. So I had this instead

[k, "#{(Float(trues.size)/ (Float(falses.size) + Float(trues.size)) * 100).round}%"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment