Skip to content

Commit

Permalink
Allow assigning both targets and local targets
Browse files Browse the repository at this point in the history
Particularly useful in tests, because writing `targets` is shorter than
writing `global_targets` and `local_targets`.
  • Loading branch information
javierm committed Jan 22, 2021
1 parent 39d68a1 commit b5ccae2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
10 changes: 9 additions & 1 deletion app/models/concerns/sdg/relatable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -57,6 +56,15 @@ def sdg_targets
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
Expand Down
12 changes: 12 additions & 0 deletions spec/models/sdg/relatable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,18 @@
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]
Expand Down

0 comments on commit b5ccae2

Please sign in to comment.