Skip to content

Commit

Permalink
Convert ComplianceMixin to has_one/virtual_delegates
Browse files Browse the repository at this point in the history
This converts the functionality defined in the virtual_has_one,
virtual_columns, and associated methods to a has_one and a pair of
virtual_delegates.

This allows these columns to also be used in SQL, and removes some of
the boilerplate code necessary for the methods that are defined.
  • Loading branch information
NickLaMuro committed Nov 14, 2018
1 parent 3b7f61a commit 890dcd7
Showing 1 changed file with 13 additions and 24 deletions.
37 changes: 13 additions & 24 deletions app/models/mixins/compliance_mixin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,19 @@ module ComplianceMixin

included do
has_many :compliances, :as => :resource, :dependent => :destroy

virtual_has_one :last_compliance, :class_name => "Compliance"

virtual_column :last_compliance_status, :type => :boolean, :uses => :last_compliance
virtual_column :last_compliance_timestamp, :type => :datetime, :uses => :last_compliance
end

def last_compliance
return @last_compliance unless @last_compliance.nil?
@last_compliance = if @association_cache.include?(:compliances)
compliances.max_by(&:timestamp)
else
compliances.order("timestamp DESC").first
end
end

def last_compliance_status
lc = last_compliance
lc.try(:compliant)
end

def last_compliance_timestamp
lc = last_compliance
lc.try(:timestamp)
has_one :last_compliance,
-> { order('"compliances"."timestamp" DESC') },
:as => :resource,
:inverse_of => :resource,
:class_name => "Compliance"

virtual_delegate :last_compliance_status,
:to => "last_compliance.compliant",
:allow_nil => true
virtual_delegate :timestamp,
:to => :last_compliance,
:allow_nil => true,
:prefix => true
end

def check_compliance
Expand Down

0 comments on commit 890dcd7

Please sign in to comment.