From d9a384f866c575cef60c5ffa986e566253063ecd Mon Sep 17 00:00:00 2001 From: Daniel Pittman Date: Thu, 14 Jul 2011 13:10:06 -0700 Subject: [PATCH] (#8316) Ruby sorting for ResourceEvents. While most of our sorting should go on in the database, there is a complex "natural" order for ResourceEvents: the 'ensure' property comes first, then everything else should be alphabetical. Since the set of events for a resource_status is usually handled distinctly, and is always small in that context, it can make sense to handle that at the Ruby level. It is also quite complex to push that logic down into the database, since SQL does not easily express the logic required. Reviewed-By: Pieter van de Bruggen --- app/models/resource_event.rb | 9 ++++++++- spec/models/resource_event_spec.rb | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 spec/models/resource_event_spec.rb diff --git a/app/models/resource_event.rb b/app/models/resource_event.rb index 433ff8782..a1b0d9f0d 100644 --- a/app/models/resource_event.rb +++ b/app/models/resource_event.rb @@ -1,7 +1,14 @@ -class ResourceEvent < ActiveRecord::Base +class ResourceEvent < ActiveRecord::Base belongs_to :resource_status serialize :desired_value serialize :previous_value serialize :historical_value + + # The "natural" order of properties is that 'ensure' comes before anything + # else, then alphabetically sorted by the property name. + def <=>(that) + [self.property == 'ensure' ? 0 : 1, self.property] <=> + [that.property == 'ensure' ? 0 : 1, that.property] + end end diff --git a/spec/models/resource_event_spec.rb b/spec/models/resource_event_spec.rb new file mode 100644 index 000000000..4a0b00ba2 --- /dev/null +++ b/spec/models/resource_event_spec.rb @@ -0,0 +1,20 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe ResourceEvent do + describe "#<=>" do + [%w{alpha ensure}, %w{zeta ensure}, %w{elfin ensure}].each do |input| + it "should sort ensure before anything else" do + input.map {|x| ResourceEvent.new(:property => x) }. + sort.map {|x| x.property }.should == + ['ensure', input.first] + end + end + + it "should sort anything else alphabetically" do + %w{elfin alpha ensure zeta equipage}.map do |x| + ResourceEvent.new(:property => x) + end.sort.map {|x| x.property }.should == + %w{ensure alpha elfin equipage zeta} + end + end +end