From 8a7f791fe53a88e116fd5e7f491c7381072133fb Mon Sep 17 00:00:00 2001 From: luispcosta Date: Mon, 13 Mar 2017 13:45:32 +0000 Subject: [PATCH] Freeze public available constants. Added tests --- lib/language_list.rb | 12 +++++++----- test/language_list_test.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/lib/language_list.rb b/lib/language_list.rb index 4b1386d..ef3897e 100644 --- a/lib/language_list.rb +++ b/lib/language_list.rb @@ -63,10 +63,10 @@ def self.find(code) warn "Reverting to hash load: #{e.message}" yaml_data = YAML.load_file(File.expand_path(File.join(File.dirname(__FILE__),'..', 'data', 'languages.yml'))) yaml_data.map{|e| LanguageInfo.new(e) } - end - ISO_639_1 = ALL_LANGUAGES.select(&:iso_639_1?) - LIVING_LANGUAGES = ALL_LANGUAGES.select(&:living?) - COMMON_LANGUAGES = ALL_LANGUAGES.select(&:common?) + end.freeze + ISO_639_1 = ALL_LANGUAGES.select(&:iso_639_1?).freeze + LIVING_LANGUAGES = ALL_LANGUAGES.select(&:living?).freeze + COMMON_LANGUAGES = ALL_LANGUAGES.select(&:common?).freeze BY_NAME = {} BY_ISO_639_1 = {} @@ -76,5 +76,7 @@ def self.find(code) BY_ISO_639_1[lang.iso_639_1] = lang if lang.iso_639_1 BY_ISO_639_3[lang.iso_639_3] = lang if lang.iso_639_3 end - + BY_NAME.freeze + BY_ISO_639_1.freeze + BY_ISO_639_3.freeze end diff --git a/test/language_list_test.rb b/test/language_list_test.rb index 96ac9fb..cdac323 100755 --- a/test/language_list_test.rb +++ b/test/language_list_test.rb @@ -97,4 +97,34 @@ def test_common_name_when_not_present english = LanguageList::LanguageInfo.find('en') assert_equal english.name, english.common_name end + + def test_cannot_change_constants + assert_raises RuntimeError, /frozen Array/i do + LanguageList::ALL_LANGUAGES[0] = nil + end + + assert_raises RuntimeError, /frozen Array/i do + LanguageList::ISO_639_1[0] = nil + end + + assert_raises RuntimeError, /frozen Array/i do + LanguageList::LIVING_LANGUAGES[0] = nil + end + + assert_raises RuntimeError, /frozen Array/i do + LanguageList::COMMON_LANGUAGES[0] = nil + end + + assert_raises RuntimeError, /frozen Array/i do + LanguageList::BY_NAME[0] = nil + end + + assert_raises RuntimeError, /frozen Array/i do + LanguageList::BY_ISO_639_1[0] = nil + end + + assert_raises RuntimeError, /frozen Array/i do + LanguageList::BY_ISO_639_3[0] = nil + end + end end