Skip to content
This repository has been archived by the owner on Mar 26, 2024. It is now read-only.

Commit

Permalink
(#8316) Ruby sorting for ResourceEvents.
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
Daniel Pittman committed Jul 14, 2011
1 parent 5a3702d commit d9a384f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
9 changes: 8 additions & 1 deletion app/models/resource_event.rb
Original file line number Diff line number Diff line change
@@ -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
20 changes: 20 additions & 0 deletions spec/models/resource_event_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit d9a384f

Please sign in to comment.