Add method to easily access a goal by code

Similar to what we do with settings, only for settings we return the
value of the setting (which is what we're going to need most of the
time), and here we return the object.
This commit is contained in:
Javi Martín
2020-11-24 19:42:37 +01:00
parent c7c8309ad1
commit d5ee1ff89c
2 changed files with 17 additions and 3 deletions

View File

@@ -8,4 +8,8 @@ class SDG::Goal < ApplicationRecord
def description def description
I18n.t("sdg.goals.goal_#{code}.description") I18n.t("sdg.goals.goal_#{code}.description")
end end
def self.[](code)
find_by!(code: code)
end
end end

View File

@@ -3,7 +3,7 @@ require "rails_helper"
describe SDG::Goal do describe SDG::Goal do
describe "validations" do describe "validations" do
it "is valid with an existent code" do it "is valid with an existent code" do
goal = SDG::Goal.where(code: "1").first_or_initialize goal = SDG::Goal[1]
expect(goal).to be_valid expect(goal).to be_valid
end end
@@ -21,8 +21,18 @@ describe SDG::Goal do
end end
end end
describe ".[]" do
it "finds existing goals by code" do
expect(SDG::Goal[1].code).to be 1
end
it "raises an exception for non-existing codes" do
expect { SDG::Goal[100] }.to raise_exception ActiveRecord::RecordNotFound
end
end
it "translates title" do it "translates title" do
goal = SDG::Goal.where(code: "1").first_or_create! goal = SDG::Goal[1]
expect(goal.title).to eq "No Poverty" expect(goal.title).to eq "No Poverty"
@@ -32,7 +42,7 @@ describe SDG::Goal do
end end
it "translates description" do it "translates description" do
goal = SDG::Goal.where(code: "1").first_or_create! goal = SDG::Goal[1]
expect(goal.description).to eq "End poverty in all its forms, everywhere." expect(goal.description).to eq "End poverty in all its forms, everywhere."