diff --git a/lib/emoji_flag.rb b/lib/emoji_flag.rb index d98aa71..a706454 100644 --- a/lib/emoji_flag.rb +++ b/lib/emoji_flag.rb @@ -5,14 +5,25 @@ module EmojiFlag OFFSET = 127_397 COUNTRY_CODE_RE = /^[A-Z]{2}$/ + @cache = {} def self.new(input) - locale = input.to_s - return '' if locale.nil? || locale.size.zero? + locale = normalize_locale(input.to_s) + return @cache[locale] if @cache.key?(locale) + + raise ArgumentError, "Locale cannot be nil or empty" if locale.nil? || locale.size.zero? code = code_for_locale(locale) - code.codepoints.collect { |codepoint| codepoint + OFFSET }.pack('U*') + raise ArgumentError, "No flag found for locale: #{locale}" if code.empty? + + flag = code.codepoints.collect { |codepoint| codepoint + OFFSET }.pack('U*') + @cache[locale] = flag + flag + end + + def self.normalize_locale(locale) + locale.strip.tr(' ', '_').tr('-', '_').downcase end def self.code_for_locale(locale)