Allow assigning both targets and local targets

Particularly useful in tests, because writing `targets` is shorter than
writing `global_targets` and `local_targets`.
This commit is contained in:
Javi Martín
2021-01-21 18:05:07 +01:00
parent 39d68a1779
commit b5ccae2f40
2 changed files with 21 additions and 1 deletions

View File

@@ -14,7 +14,6 @@ module SDG::Relatable
through: :sdg_relations,
source: :related_sdg,
source_type: "SDG::Target"
alias_method :sdg_targets=, :sdg_global_targets=
has_one :sdg_review, as: :relatable, dependent: :destroy, class_name: "SDG::Review"
end
@@ -57,6 +56,15 @@ module SDG::Relatable
sdg_global_targets + sdg_local_targets
end
def sdg_targets=(targets)
global_targets, local_targets = targets.partition { |target| target.class.name == "SDG::Target" }
transaction do
self.sdg_global_targets = global_targets
self.sdg_local_targets = local_targets
end
end
def sdg_goal_list
sdg_goals.order(:code).map(&:code).join(", ")
end

View File

@@ -69,6 +69,18 @@ describe SDG::Relatable do
end
end
describe "#sdg_targets=" do
it "assigns both targets and local targets" do
global_targets = [SDG::Target[2.2], SDG::Target[1.2]]
local_targets = %w[2.2.1 3.1.1].map { |code| create(:sdg_local_target, code: code) }
relatable.sdg_targets = global_targets + local_targets
expect(relatable.sdg_global_targets).to match_array global_targets
expect(relatable.sdg_local_targets).to match_array local_targets
end
end
describe "#sdg_local_targets" do
it "can assign local targets to a model" do
relatable.sdg_local_targets = [local_target, another_local_target]