Skip to content
Snippets Groups Projects
Commit fca66e17 authored by Markus Reiter's avatar Markus Reiter
Browse files

Make parsing locales more robust.

parent 7af8cdcb
No related branches found
No related tags found
No related merge requests found
class Locale
class ParserError < ::RuntimeError
class ParserError < StandardError
end
LANGUAGE_REGEX = /(?:[a-z]{2})/
REGION_REGEX = /(?:[A-Z]{2})/
SCRIPT_REGEX = /(?:[A-Z][a-z]{3})/
LANGUAGE_REGEX = /(?:[a-z]{2,3})/ # ISO 639-1 or ISO 639-2
REGION_REGEX = /(?:[A-Z]{2})/ # ISO 3166-1
SCRIPT_REGEX = /(?:[A-Z][a-z]{3})/ # ISO 15924
LOCALE_REGEX = /^(#{LANGUAGE_REGEX})?(?:(?:^|-)(#{REGION_REGEX}))?(?:(?:^|-)(#{SCRIPT_REGEX}))?$/
LOCALE_REGEX = /\A((?:#{LANGUAGE_REGEX}|#{REGION_REGEX}|#{SCRIPT_REGEX})(?:\-|$)){1,3}\Z/
def self.parse(string)
language, region, script = string.to_s.scan(LOCALE_REGEX)[0]
string = string.to_s
if language.nil? && region.nil? && script.nil?
raise ParserError, "'#{string}' cannot be parsed to a #{self.class}"
if string !~ LOCALE_REGEX
raise ParserError, "'#{string}' cannot be parsed to a #{self}"
end
scan = proc do |regex|
string.scan(/(?:\-|^)(#{regex})(?:\-|$)/).flatten.first
end
language = scan.call(LANGUAGE_REGEX)
region = scan.call(REGION_REGEX)
script = scan.call(SCRIPT_REGEX)
new(language, region, script)
end
......
require "testing_env"
require "locale"
require "os/mac"
class OSMacLanguageTests < Homebrew::TestCase
LANGUAGE_REGEX = /\A[a-z]{2}(-[A-Z]{2})?(-[A-Z][a-z]{3})?\Z/
def test_languages_format
OS::Mac.languages.each do |language|
assert_match LANGUAGE_REGEX, language
assert_nothing_raised do
Locale.parse(language)
end
end
end
def test_language_format
assert_match LANGUAGE_REGEX, OS::Mac.language
assert_nothing_raised do
Locale.parse(OS::Mac.language)
end
end
end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment