From d5ee1ff89c231f9b163fed9386cefa0d29d25200 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Tue, 24 Nov 2020 19:42:37 +0100 Subject: [PATCH] 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. --- app/models/sdg/goal.rb | 4 ++++ spec/models/sdg/goal_spec.rb | 16 +++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/app/models/sdg/goal.rb b/app/models/sdg/goal.rb index eb83d4ecb..f65488ca7 100644 --- a/app/models/sdg/goal.rb +++ b/app/models/sdg/goal.rb @@ -8,4 +8,8 @@ class SDG::Goal < ApplicationRecord def description I18n.t("sdg.goals.goal_#{code}.description") end + + def self.[](code) + find_by!(code: code) + end end diff --git a/spec/models/sdg/goal_spec.rb b/spec/models/sdg/goal_spec.rb index 831ce85d6..94d20710b 100644 --- a/spec/models/sdg/goal_spec.rb +++ b/spec/models/sdg/goal_spec.rb @@ -3,7 +3,7 @@ require "rails_helper" describe SDG::Goal do describe "validations" 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 end @@ -21,8 +21,18 @@ describe SDG::Goal do 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 - goal = SDG::Goal.where(code: "1").first_or_create! + goal = SDG::Goal[1] expect(goal.title).to eq "No Poverty" @@ -32,7 +42,7 @@ describe SDG::Goal do end 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."