From e17819dc28266dd20ed5275884bdf97e0338d919 Mon Sep 17 00:00:00 2001 From: Vraj Mohan Date: Thu, 19 Dec 2024 16:44:31 -0800 Subject: [PATCH] Use scope and class method to clean up implementation --- app/models/email_address.rb | 5 +++++ app/models/user.rb | 6 +++--- spec/models/user_spec.rb | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/app/models/email_address.rb b/app/models/email_address.rb index ca3a7b53c01..f8eeafa327d 100644 --- a/app/models/email_address.rb +++ b/app/models/email_address.rb @@ -49,6 +49,11 @@ def mil_email? email.end_with?('.mil') end + def self.last_sign_in + order('last_sign_in_at DESC NULLS LAST').first + end + + class << self def find_with_email(email) return nil if !email.is_a?(String) || email.empty? diff --git a/app/models/user.rb b/app/models/user.rb index 41bedac7df4..2eca557512a 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -65,7 +65,7 @@ class User < ApplicationRecord attr_accessor :asserted_attributes, :email def confirmed_email_addresses - email_addresses.where.not(confirmed_at: nil).order('last_sign_in_at DESC NULLS LAST') + email_addresses.confirmed end def fully_registered? @@ -73,7 +73,7 @@ def fully_registered? end def confirmed? - email_addresses.where.not(confirmed_at: nil).any? + confirmed_email_addresses.any? end def has_fed_or_mil_email? @@ -522,7 +522,7 @@ def reload(...) end def last_sign_in_email_address - confirmed_email_addresses.first + email_addresses.confirmed.last_sign_in end private diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 38353bf3e52..af90db40662 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -1721,4 +1721,39 @@ def it_should_not_send_survey end end end + + describe '#last_sign_in_email_address' do + let(:user) { create(:user) } + + let!(:last_sign_in_email_address) do + create( + :email_address, + email: 'last_sign_in@email.com', + user: user, + last_sign_in_at: 1.minute.ago, + ) + end + + let!(:older_sign_in_email_address) do + create( + :email_address, + email: 'older_sign_in@email.com', + user: user, + last_sign_in_at: 1.hour.ago, + ) + end + + let!(:never_signed_in_email_address) do + create( + :email_address, + email: 'never_signed_in@email.com', + user: user, + last_sign_in_at: nil, + ) + end + + it 'returns the last signed in email address' do + expect(user.last_sign_in_email_address).to eq(last_sign_in_email_address) + end + end end