diff options
| author | Markus Reiter | 2016-10-03 04:03:26 +0200 |
|---|---|---|
| committer | GitHub | 2016-10-03 04:03:26 +0200 |
| commit | 35ee2831086e923e7fcaf75fb440b01312e3f9c5 (patch) | |
| tree | 6f3efd1eb351125333fbe10390bd3a9e5b7b87e0 /Library/Homebrew/locale.rb | |
| parent | 7d31a70373edae4d8e78d91a4cbc05324bebc3ba (diff) | |
| parent | e2b3753fd91c47beeb3227a1c0df4c0dfa6026fc (diff) | |
| download | brew-1.0.6.tar.bz2 | |
Merge pull request #906 from reitermarkus/os-language1.0.6
Make `MacOS.language` less opinionated and add `language` stanza.
Diffstat (limited to 'Library/Homebrew/locale.rb')
| -rw-r--r-- | Library/Homebrew/locale.rb | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/Library/Homebrew/locale.rb b/Library/Homebrew/locale.rb new file mode 100644 index 000000000..1aff33dae --- /dev/null +++ b/Library/Homebrew/locale.rb @@ -0,0 +1,68 @@ +class Locale + class ParserError < ::RuntimeError + end + + LANGUAGE_REGEX = /(?:[a-z]{2})/ + REGION_REGEX = /(?:[A-Z]{2})/ + SCRIPT_REGEX = /(?:[A-Z][a-z]{3})/ + + LOCALE_REGEX = /^(#{LANGUAGE_REGEX})?(?:(?:^|-)(#{REGION_REGEX}))?(?:(?:^|-)(#{SCRIPT_REGEX}))?$/ + + def self.parse(string) + language, region, script = string.to_s.scan(LOCALE_REGEX)[0] + + if language.nil? && region.nil? && script.nil? + raise ParserError, "'#{string}' cannot be parsed to a #{self.class}" + end + + new(language, region, script) + end + + attr_reader :language, :region, :script + + def initialize(language, region, script) + if language.nil? && region.nil? && script.nil? + raise ArgumentError, "#{self.class} cannot be empty" + end + + { + language: language, + region: region, + script: script, + }.each do |key, value| + next if value.nil? + + regex = self.class.const_get("#{key.upcase}_REGEX") + raise ParserError, "'#{value}' does not match #{regex}" unless value =~ regex + instance_variable_set(:"@#{key}", value) + end + + self + end + + def include?(other) + other = self.class.parse(other) unless other.is_a?(self.class) + + [:language, :region, :script].all? { |var| + if other.public_send(var).nil? + true + else + public_send(var) == other.public_send(var) + end + } + end + + def eql?(other) + other = self.class.parse(other) unless other.is_a?(self.class) + [:language, :region, :script].all? { |var| + public_send(var) == other.public_send(var) + } + rescue ParserError + false + end + alias == eql? + + def to_s + [@language, @region, @script].compact.join("-") + end +end |
