From 1bcb9d4bb131aee047628e9d407877369e2ed5d5 Mon Sep 17 00:00:00 2001 From: Andrew Tomaka Date: Sun, 26 Apr 2015 11:42:19 -0400 Subject: [PATCH] Better leader last_action calculation --- app.rb | 16 ++++------------ models/leader.rb | 15 +++++++++++++++ views/index.erb | 4 ++-- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/app.rb b/app.rb index 9393b19..a256a69 100644 --- a/app.rb +++ b/app.rb @@ -7,20 +7,12 @@ get '/' do @raids = Raid.order('created_at DESC').page(params[:page]) leaders = Leader.all last_update = leaders.first ? leaders.first.created_at : DateTime.new(0) - rebuild_leaders if last_update + 300 < DateTime.now - - @top20 = leaders.map { |l| { user: l.leader, date: nil } } - - @top20.each_with_index do |hash, i| - @raids.each do |raid| - if raid.attacker == hash[:user] || raid.defender == hash[:user] - @top20[i][:date] = raid.created_at - break - end - end + if last_update + 300 < DateTime.now + rebuild_leaders end - @top20 = @top20.select { |h| h[:date] }.sort_by { |h| h[:date] } + @top20.reject { |h| h[:date] } + leaders = Leader.all.includes(:last_attack, :last_defense) + @top20 = leaders.select { |l| l.last_action }.sort_by { |l| l.last_action } + leaders.reject { |l| l.last_action } erb :index end diff --git a/models/leader.rb b/models/leader.rb index 918b516..50517ec 100644 --- a/models/leader.rb +++ b/models/leader.rb @@ -1,3 +1,18 @@ class Leader < ActiveRecord::Base + has_one :last_attack, foreign_key: :attacker, primary_key: :leader, class_name: 'Raid' + has_one :last_defense, foreign_key: :defender, primary_key: :leader, class_name: 'Raid' + def last_action + if last_attack == nil && last_defense == nil + @last_action = nil + elsif last_defense == nil + @last_action = last_attack.created_at + elsif last_attack == nil + @last_action = last_defense.created_at + else + @last_action = (last_attack.created_at > last_defense.created_at) ? last_attack.created_at : last_defense.created_at + end + + return @last_action + end end diff --git a/views/index.erb b/views/index.erb index fa278a8..c65778a 100644 --- a/views/index.erb +++ b/views/index.erb @@ -34,7 +34,7 @@
<%= Time.now.utc.strftime('%H:%M on %m-%d-%Y') %>