Allow target and local target comparison

This way we'll be able to sort a mixed collection of targets and local
targets.
This commit is contained in:
Javi Martín
2021-01-20 19:15:43 +01:00
parent e96f45ba39
commit d3f72b100e
4 changed files with 46 additions and 8 deletions

View File

@@ -17,10 +17,12 @@ class SDG::LocalTarget < ApplicationRecord
belongs_to :target
def <=>(local_target)
return unless local_target.class == self.class
[target, numeric_subcode] <=> [local_target.target, local_target.numeric_subcode]
def <=>(any_target)
if any_target.class == self.class
[target, numeric_subcode] <=> [any_target.target, any_target.numeric_subcode]
elsif any_target.class == target.class
-1 * (any_target <=> self)
end
end
protected

View File

@@ -12,10 +12,12 @@ class SDG::Target < ApplicationRecord
I18n.t("sdg.goals.goal_#{goal.code}.targets.target_#{code_key}.title")
end
def <=>(target)
return unless target.class == self.class
[goal.code, numeric_subcode] <=> [target.goal.code, target.numeric_subcode]
def <=>(any_target)
if any_target.class == self.class
[goal.code, numeric_subcode] <=> [any_target.goal.code, any_target.numeric_subcode]
elsif any_target.class.name == "SDG::LocalTarget"
[self, -1] <=> [any_target.target, 1]
end
end
def self.[](code)

View File

@@ -73,5 +73,13 @@ describe SDG::LocalTarget do
expect(local_target).to be > lesser_local_target
expect(local_target).to be < greater_local_target
end
it "can be compared against global targets" do
lesser_target = build(:sdg_target, code: "10.A", goal: SDG::Goal[10])
greater_target = build(:sdg_target, code: "11.1", goal: SDG::Goal[11])
expect(local_target).to be > lesser_target
expect(local_target).to be < greater_target
end
end
end

View File

@@ -61,6 +61,32 @@ describe SDG::Target do
expect(target).to be > lesser_target
expect(target).to be < greater_target
end
context "comparing with a local target" do
it "compares using the goal first" do
lesser_local_target = build(:sdg_local_target, code: "2.1.1")
greater_local_target = build(:sdg_local_target, code: "11.1.2")
expect(target).to be > lesser_local_target
expect(target).to be < greater_local_target
end
it "compares using the target when the goal is the same" do
lesser_target = build(:sdg_target, code: "10.2", goal: goal)
greater_target = build(:sdg_target, code: "10.A", goal: goal)
lesser_local_target = build(:sdg_local_target, code: "10.2.25", target: lesser_target)
greater_local_target = build(:sdg_local_target, code: "10.A.1", target: greater_target)
expect(target).to be > lesser_local_target
expect(target).to be < greater_local_target
end
it "is smaller than a local target belonging to it" do
local_target = build(:sdg_local_target, target: target, code: "10.19.1")
expect(target).to be < local_target
end
end
end
describe ".[]" do