repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/list_test.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/list_test.rb
require "test_helper" class PublicSuffix::ListTest < Minitest::Test def setup @list = PublicSuffix::List.new end def teardown PublicSuffix::List.default = nil end def test_initialize assert_instance_of PublicSuffix::List, @list assert_equal 0, @list.size end def test_equality_with_self list = PublicSuffix::List.new assert_equal list, list end def test_equality_with_internals rule = PublicSuffix::Rule.factory("com") assert_equal PublicSuffix::List.new.add(rule), PublicSuffix::List.new.add(rule) end def test_each_without_block list = PublicSuffix::List.parse(<<LIST) alpha beta LIST assert_kind_of Enumerator, list.each assert_equal 2, list.each.count assert_equal PublicSuffix::Rule.factory("alpha"), list.each.first end def test_each_with_block list = PublicSuffix::List.parse(<<LIST) alpha beta LIST entries = [] list.each { |r| entries << r } assert_equal 2, entries.count assert_equal PublicSuffix::Rule.factory("alpha"), entries.first end def test_add assert_equal @list, @list.add(PublicSuffix::Rule.factory("foo")) assert_equal @list, @list << PublicSuffix::Rule.factory("bar") assert_equal 2, @list.size end def test_add_should_recreate_index @list = PublicSuffix::List.parse("com") assert_equal PublicSuffix::Rule.factory("com"), @list.find("google.com") assert_equal @list.default_rule, @list.find("google.net") @list << PublicSuffix::Rule.factory("net") assert_equal PublicSuffix::Rule.factory("com"), @list.find("google.com") assert_equal PublicSuffix::Rule.factory("net"), @list.find("google.net") end def test_empty? assert @list.empty? @list.add(PublicSuffix::Rule.factory("")) assert !@list.empty? end def test_size assert_equal 0, @list.size assert_equal @list, @list.add(PublicSuffix::Rule.factory("")) assert_equal 1, @list.size end def test_clear assert_equal 0, @list.size assert_equal @list, @list.add(PublicSuffix::Rule.factory("")) assert_equal 1, @list.size assert_equal @list, @list.clear assert_equal 0, @list.size end def test_find list = PublicSuffix::List.parse(<<LIST) // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // ===BEGIN ICANN DOMAINS=== // com com // uk *.uk *.sch.uk !bl.uk !british-library.uk // io io // ===END ICANN DOMAINS=== // ===BEGIN PRIVATE DOMAINS=== // Google, Inc. blogspot.com // ===END PRIVATE DOMAINS=== LIST # match IANA assert_equal PublicSuffix::Rule.factory("com"), list.find("example.com") assert_equal PublicSuffix::Rule.factory("com"), list.find("foo.example.com") # match wildcard assert_equal PublicSuffix::Rule.factory("*.uk"), list.find("example.uk") assert_equal PublicSuffix::Rule.factory("*.uk"), list.find("example.co.uk") assert_equal PublicSuffix::Rule.factory("*.uk"), list.find("foo.example.co.uk") # match exception assert_equal PublicSuffix::Rule.factory("!british-library.uk"), list.find("british-library.uk") assert_equal PublicSuffix::Rule.factory("!british-library.uk"), list.find("foo.british-library.uk") # match default rule assert_equal PublicSuffix::Rule.factory("*"), list.find("test") assert_equal PublicSuffix::Rule.factory("*"), list.find("example.test") assert_equal PublicSuffix::Rule.factory("*"), list.find("foo.example.test") # match private assert_equal PublicSuffix::Rule.factory("blogspot.com", private: true), list.find("blogspot.com") assert_equal PublicSuffix::Rule.factory("blogspot.com", private: true), list.find("foo.blogspot.com") end def test_select assert_equal 2, list.send(:select, "british-library.uk").size end def test_select_name_blank assert_equal [], list.send(:select, nil) assert_equal [], list.send(:select, "") assert_equal [], list.send(:select, " ") end def test_select_ignore_private list = PublicSuffix::List.new list.add r1 = PublicSuffix::Rule.factory("io") list.add r2 = PublicSuffix::Rule.factory("example.io", private: true) assert_equal list.send(:select, "foo.io"), [r1] assert_equal list.send(:select, "example.io"), [r1, r2] assert_equal list.send(:select, "foo.example.io"), [r1, r2] assert_equal list.send(:select, "foo.io", ignore_private: false), [r1] assert_equal list.send(:select, "example.io", ignore_private: false), [r1, r2] assert_equal list.send(:select, "foo.example.io", ignore_private: false), [r1, r2] assert_equal list.send(:select, "foo.io", ignore_private: true), [r1] assert_equal list.send(:select, "example.io", ignore_private: true), [r1] assert_equal list.send(:select, "foo.example.io", ignore_private: true), [r1] end def test_self_default_getter PublicSuffix::List.default = nil assert_nil(PublicSuffix::List.class_eval { @default }) PublicSuffix::List.default refute_nil(PublicSuffix::List.class_eval { @default }) end def test_self_default_setter PublicSuffix::List.default refute_nil(PublicSuffix::List.class_eval { @default }) PublicSuffix::List.default = nil assert_nil(PublicSuffix::List.class_eval { @default }) end def test_self_parse list = PublicSuffix::List.parse(<<LIST) // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // ===BEGIN ICANN DOMAINS=== // com com // uk *.uk !british-library.uk // ===END ICANN DOMAINS=== // ===BEGIN PRIVATE DOMAINS=== // Google, Inc. blogspot.com // ===END PRIVATE DOMAINS=== LIST assert_instance_of PublicSuffix::List, list assert_equal 4, list.size rules = %w( com *.uk !british-library.uk blogspot.com ).map { |name| PublicSuffix::Rule.factory(name) } assert_equal rules, list.each.to_a # private domains assert_equal false, list.find("com").private assert_equal true, list.find("blogspot.com").private end private def list @_list ||= PublicSuffix::List.parse(<<LIST) // com : http://en.wikipedia.org/wiki/.com com // uk : http://en.wikipedia.org/wiki/.uk *.uk *.sch.uk !bl.uk !british-library.uk LIST end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/find_profiler.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/find_profiler.rb
$LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "memory_profiler" require "public_suffix" PublicSuffix::List.default report = MemoryProfiler.report do PublicSuffix::List.default.find("www.example.com") end report.pretty_print
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/list_profsize.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/list_profsize.rb
$LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require_relative "object_binsize" require "public_suffix" list = PublicSuffix::List.default puts "#{list.size} rules:" prof = ObjectBinsize.new prof.report(PublicSuffix::List.default, label: "PublicSuffix::List size") prof.report(PublicSuffix::List.default.instance_variable_get(:@rules), label: "Size of rules")
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/initialization_profiler.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/initialization_profiler.rb
$LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "memory_profiler" require "public_suffix" report = MemoryProfiler.report do PublicSuffix::List.default end report.pretty_print # report.pretty_print(to_file: 'profiler-%s-%d.txt' % [ARGV[0], Time.now.to_i])
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/object_binsize.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/object_binsize.rb
require 'tempfile' # A very simple memory profiles that checks the full size of a variable # by serializing into a binary file. # # Yes, I know this is very rough, but there are cases where ObjectSpace.memsize_of # doesn't cooperate, and this is one of the possible workarounds. # # For certain cases, it works (TM). class ObjectBinsize def measure(var, label: nil) dump(var, label: label) end def report(var, label: nil, padding: 10) file = measure(var, label: label) size = format_integer(file.size) name = label || File.basename(file.path) printf("%#{padding}s %s\n", size, name) end private def dump(var, **args) file = Tempfile.new(args[:label].to_s) file.write(Marshal.dump(var)) file ensure file.close end def format_integer(int) int.to_s.reverse.gsub(/...(?=.)/, '\&,').reverse end end if __FILE__ == $0 prof = ObjectBinsize.new prof.report(nil, label: "nil") prof.report(false, label: "false") prof.report(true, label: "true") prof.report(0, label: "integer") prof.report("", label: "empty string") prof.report({}, label: "empty hash") prof.report({}, label: "empty array") prof.report({ foo: "1" }, label: "hash 1 item (symbol)") prof.report({ foo: "1", bar: 2 }, label: "hash 2 items (symbol)") prof.report({ "foo" => "1" }, label: "hash 1 item (string)") prof.report({ "foo" => "1", "bar" => 2 }, label: "hash 2 items (string)") prof.report("big string" * 200, label: "big string * 200") end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/domain_profiler.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/domain_profiler.rb
$LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "memory_profiler" require "public_suffix" PublicSuffix::List.default report = MemoryProfiler.report do PublicSuffix.domain("www.example.com") end report.pretty_print
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/find_profiler_jp.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/profilers/find_profiler_jp.rb
$LOAD_PATH.unshift File.expand_path("../../lib", __dir__) require "memory_profiler" require "public_suffix" PublicSuffix::List.default report = MemoryProfiler.report do PublicSuffix::List.default.find("a.b.ide.kyoto.jp") end report.pretty_print
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix.rb
# = Public Suffix # # Domain name parser based on the Public Suffix List. # # Copyright (c) 2009-2018 Simone Carletti <weppos@weppos.net> require_relative "public_suffix/domain" require_relative "public_suffix/version" require_relative "public_suffix/errors" require_relative "public_suffix/rule" require_relative "public_suffix/list" # PublicSuffix is a Ruby domain name parser based on the Public Suffix List. # # The [Public Suffix List](https://publicsuffix.org) is a cross-vendor initiative # to provide an accurate list of domain name suffixes. # # The Public Suffix List is an initiative of the Mozilla Project, # but is maintained as a community resource. It is available for use in any software, # but was originally created to meet the needs of browser manufacturers. module PublicSuffix DOT = ".".freeze BANG = "!".freeze STAR = "*".freeze # Parses +name+ and returns the {PublicSuffix::Domain} instance. # # @example Parse a valid domain # PublicSuffix.parse("google.com") # # => #<PublicSuffix::Domain:0x007fec2e51e588 @sld="google", @tld="com", @trd=nil> # # @example Parse a valid subdomain # PublicSuffix.parse("www.google.com") # # => #<PublicSuffix::Domain:0x007fec276d4cf8 @sld="google", @tld="com", @trd="www"> # # @example Parse a fully qualified domain # PublicSuffix.parse("google.com.") # # => #<PublicSuffix::Domain:0x007fec257caf38 @sld="google", @tld="com", @trd=nil> # # @example Parse a fully qualified domain (subdomain) # PublicSuffix.parse("www.google.com.") # # => #<PublicSuffix::Domain:0x007fec27b6bca8 @sld="google", @tld="com", @trd="www"> # # @example Parse an invalid (unlisted) domain # PublicSuffix.parse("x.yz") # # => #<PublicSuffix::Domain:0x007fec2f49bec0 @sld="x", @tld="yz", @trd=nil> # # @example Parse an invalid (unlisted) domain with strict checking (without applying the default * rule) # PublicSuffix.parse("x.yz", default_rule: nil) # # => PublicSuffix::DomainInvalid: `x.yz` is not a valid domain # # @example Parse an URL (not supported, only domains) # PublicSuffix.parse("http://www.google.com") # # => PublicSuffix::DomainInvalid: http://www.google.com is not expected to contain a scheme # # # @param [String, #to_s] name The domain name or fully qualified domain name to parse. # @param [PublicSuffix::List] list The rule list to search, defaults to the default {PublicSuffix::List} # @param [Boolean] ignore_private # @return [PublicSuffix::Domain] # # @raise [PublicSuffix::DomainInvalid] # If domain is not a valid domain. # @raise [PublicSuffix::DomainNotAllowed] # If a rule for +domain+ is found, but the rule doesn't allow +domain+. def self.parse(name, list: List.default, default_rule: list.default_rule, ignore_private: false) what = normalize(name) raise what if what.is_a?(DomainInvalid) rule = list.find(what, default: default_rule, ignore_private: ignore_private) # rubocop:disable Style/IfUnlessModifier if rule.nil? raise DomainInvalid, "`#{what}` is not a valid domain" end if rule.decompose(what).last.nil? raise DomainNotAllowed, "`#{what}` is not allowed according to Registry policy" end # rubocop:enable Style/IfUnlessModifier decompose(what, rule) end # Checks whether +domain+ is assigned and allowed, without actually parsing it. # # This method doesn't care whether domain is a domain or subdomain. # The validation is performed using the default {PublicSuffix::List}. # # @example Validate a valid domain # PublicSuffix.valid?("example.com") # # => true # # @example Validate a valid subdomain # PublicSuffix.valid?("www.example.com") # # => true # # @example Validate a not-listed domain # PublicSuffix.valid?("example.tldnotlisted") # # => true # # @example Validate a not-listed domain with strict checking (without applying the default * rule) # PublicSuffix.valid?("example.tldnotlisted") # # => true # PublicSuffix.valid?("example.tldnotlisted", default_rule: nil) # # => false # # @example Validate a fully qualified domain # PublicSuffix.valid?("google.com.") # # => true # PublicSuffix.valid?("www.google.com.") # # => true # # @example Check an URL (which is not a valid domain) # PublicSuffix.valid?("http://www.example.com") # # => false # # # @param [String, #to_s] name The domain name or fully qualified domain name to validate. # @param [Boolean] ignore_private # @return [Boolean] def self.valid?(name, list: List.default, default_rule: list.default_rule, ignore_private: false) what = normalize(name) return false if what.is_a?(DomainInvalid) rule = list.find(what, default: default_rule, ignore_private: ignore_private) !rule.nil? && !rule.decompose(what).last.nil? end # Attempt to parse the name and returns the domain, if valid. # # This method doesn't raise. Instead, it returns nil if the domain is not valid for whatever reason. # # @param [String, #to_s] name The domain name or fully qualified domain name to parse. # @param [PublicSuffix::List] list The rule list to search, defaults to the default {PublicSuffix::List} # @param [Boolean] ignore_private # @return [String] def self.domain(name, **options) parse(name, **options).domain rescue PublicSuffix::Error nil end # private def self.decompose(name, rule) left, right = rule.decompose(name) parts = left.split(DOT) # If we have 0 parts left, there is just a tld and no domain or subdomain # If we have 1 part left, there is just a tld, domain and not subdomain # If we have 2 parts left, the last part is the domain, the other parts (combined) are the subdomain tld = right sld = parts.empty? ? nil : parts.pop trd = parts.empty? ? nil : parts.join(DOT) Domain.new(tld, sld, trd) end # Pretend we know how to deal with user input. def self.normalize(name) name = name.to_s.dup name.strip! name.chomp!(DOT) name.downcase! return DomainInvalid.new("Name is blank") if name.empty? return DomainInvalid.new("Name starts with a dot") if name.start_with?(DOT) return DomainInvalid.new("%s is not expected to contain a scheme" % name) if name.include?("://") name end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/version.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/version.rb
# = Public Suffix # # Domain name parser based on the Public Suffix List. # # Copyright (c) 2009-2018 Simone Carletti <weppos@weppos.net> module PublicSuffix # The current library version. VERSION = "3.0.3".freeze end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/errors.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/errors.rb
# = Public Suffix # # Domain name parser based on the Public Suffix List. # # Copyright (c) 2009-2018 Simone Carletti <weppos@weppos.net> module PublicSuffix class Error < StandardError end # Raised when trying to parse an invalid name. # A name is considered invalid when no rule is found in the definition list. # # @example # # PublicSuffix.parse("nic.test") # # => PublicSuffix::DomainInvalid # # PublicSuffix.parse("http://www.nic.it") # # => PublicSuffix::DomainInvalid # class DomainInvalid < Error end # Raised when trying to parse a name that matches a suffix. # # @example # # PublicSuffix.parse("nic.do") # # => PublicSuffix::DomainNotAllowed # # PublicSuffix.parse("www.nic.do") # # => PublicSuffix::Domain # class DomainNotAllowed < DomainInvalid end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/domain.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/domain.rb
# = Public Suffix # # Domain name parser based on the Public Suffix List. # # Copyright (c) 2009-2018 Simone Carletti <weppos@weppos.net> module PublicSuffix # Domain represents a domain name, composed by a TLD, SLD and TRD. class Domain # Splits a string into the labels, that is the dot-separated parts. # # The input is not validated, but it is assumed to be a valid domain name. # # @example # # name_to_labels('example.com') # # => ['example', 'com'] # # name_to_labels('example.co.uk') # # => ['example', 'co', 'uk'] # # @param name [String, #to_s] The domain name to split. # @return [Array<String>] def self.name_to_labels(name) name.to_s.split(DOT) end attr_reader :tld, :sld, :trd # Creates and returns a new {PublicSuffix::Domain} instance. # # @overload initialize(tld) # Initializes with a +tld+. # @param [String] tld The TLD (extension) # @overload initialize(tld, sld) # Initializes with a +tld+ and +sld+. # @param [String] tld The TLD (extension) # @param [String] sld The TRD (domain) # @overload initialize(tld, sld, trd) # Initializes with a +tld+, +sld+ and +trd+. # @param [String] tld The TLD (extension) # @param [String] sld The SLD (domain) # @param [String] tld The TRD (subdomain) # # @yield [self] Yields on self. # @yieldparam [PublicSuffix::Domain] self The newly creates instance # # @example Initialize with a TLD # PublicSuffix::Domain.new("com") # # => #<PublicSuffix::Domain @tld="com"> # # @example Initialize with a TLD and SLD # PublicSuffix::Domain.new("com", "example") # # => #<PublicSuffix::Domain @tld="com", @trd=nil> # # @example Initialize with a TLD, SLD and TRD # PublicSuffix::Domain.new("com", "example", "wwww") # # => #<PublicSuffix::Domain @tld="com", @trd=nil, @sld="example"> # def initialize(*args) @tld, @sld, @trd = args yield(self) if block_given? end # Returns a string representation of this object. # # @return [String] def to_s name end # Returns an array containing the domain parts. # # @return [Array<String, nil>] # # @example # # PublicSuffix::Domain.new("google.com").to_a # # => [nil, "google", "com"] # # PublicSuffix::Domain.new("www.google.com").to_a # # => [nil, "google", "com"] # def to_a [@trd, @sld, @tld] end # Returns the full domain name. # # @return [String] # # @example Gets the domain name of a domain # PublicSuffix::Domain.new("com", "google").name # # => "google.com" # # @example Gets the domain name of a subdomain # PublicSuffix::Domain.new("com", "google", "www").name # # => "www.google.com" # def name [@trd, @sld, @tld].compact.join(DOT) end # Returns a domain-like representation of this object # if the object is a {#domain?}, <tt>nil</tt> otherwise. # # PublicSuffix::Domain.new("com").domain # # => nil # # PublicSuffix::Domain.new("com", "google").domain # # => "google.com" # # PublicSuffix::Domain.new("com", "google", "www").domain # # => "www.google.com" # # This method doesn't validate the input. It handles the domain # as a valid domain name and simply applies the necessary transformations. # # This method returns a FQD, not just the domain part. # To get the domain part, use <tt>#sld</tt> (aka second level domain). # # PublicSuffix::Domain.new("com", "google", "www").domain # # => "google.com" # # PublicSuffix::Domain.new("com", "google", "www").sld # # => "google" # # @see #domain? # @see #subdomain # # @return [String] def domain [@sld, @tld].join(DOT) if domain? end # Returns a subdomain-like representation of this object # if the object is a {#subdomain?}, <tt>nil</tt> otherwise. # # PublicSuffix::Domain.new("com").subdomain # # => nil # # PublicSuffix::Domain.new("com", "google").subdomain # # => nil # # PublicSuffix::Domain.new("com", "google", "www").subdomain # # => "www.google.com" # # This method doesn't validate the input. It handles the domain # as a valid domain name and simply applies the necessary transformations. # # This method returns a FQD, not just the subdomain part. # To get the subdomain part, use <tt>#trd</tt> (aka third level domain). # # PublicSuffix::Domain.new("com", "google", "www").subdomain # # => "www.google.com" # # PublicSuffix::Domain.new("com", "google", "www").trd # # => "www" # # @see #subdomain? # @see #domain # # @return [String] def subdomain [@trd, @sld, @tld].join(DOT) if subdomain? end # Checks whether <tt>self</tt> looks like a domain. # # This method doesn't actually validate the domain. # It only checks whether the instance contains # a value for the {#tld} and {#sld} attributes. # # @example # # PublicSuffix::Domain.new("com").domain? # # => false # # PublicSuffix::Domain.new("com", "google").domain? # # => true # # PublicSuffix::Domain.new("com", "google", "www").domain? # # => true # # # This is an invalid domain, but returns true # # because this method doesn't validate the content. # PublicSuffix::Domain.new("com", nil).domain? # # => true # # @see #subdomain? # # @return [Boolean] def domain? !(@tld.nil? || @sld.nil?) end # Checks whether <tt>self</tt> looks like a subdomain. # # This method doesn't actually validate the subdomain. # It only checks whether the instance contains # a value for the {#tld}, {#sld} and {#trd} attributes. # If you also want to validate the domain, # use {#valid_subdomain?} instead. # # @example # # PublicSuffix::Domain.new("com").subdomain? # # => false # # PublicSuffix::Domain.new("com", "google").subdomain? # # => false # # PublicSuffix::Domain.new("com", "google", "www").subdomain? # # => true # # # This is an invalid domain, but returns true # # because this method doesn't validate the content. # PublicSuffix::Domain.new("com", "example", nil).subdomain? # # => true # # @see #domain? # # @return [Boolean] def subdomain? !(@tld.nil? || @sld.nil? || @trd.nil?) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/list.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/list.rb
# = Public Suffix # # Domain name parser based on the Public Suffix List. # # Copyright (c) 2009-2018 Simone Carletti <weppos@weppos.net> module PublicSuffix # A {PublicSuffix::List} is a collection of one # or more {PublicSuffix::Rule}. # # Given a {PublicSuffix::List}, # you can add or remove {PublicSuffix::Rule}, # iterate all items in the list or search for the first rule # which matches a specific domain name. # # # Create a new list # list = PublicSuffix::List.new # # # Push two rules to the list # list << PublicSuffix::Rule.factory("it") # list << PublicSuffix::Rule.factory("com") # # # Get the size of the list # list.size # # => 2 # # # Search for the rule matching given domain # list.find("example.com") # # => #<PublicSuffix::Rule::Normal> # list.find("example.org") # # => nil # # You can create as many {PublicSuffix::List} you want. # The {PublicSuffix::List.default} rule list is used # to tokenize and validate a domain. # class List DEFAULT_LIST_PATH = File.expand_path("../../data/list.txt", __dir__) # Gets the default rule list. # # Initializes a new {PublicSuffix::List} parsing the content # of {PublicSuffix::List.default_list_content}, if required. # # @return [PublicSuffix::List] def self.default(**options) @default ||= parse(File.read(DEFAULT_LIST_PATH), options) end # Sets the default rule list to +value+. # # @param value [PublicSuffix::List] the new list # @return [PublicSuffix::List] def self.default=(value) @default = value end # Parse given +input+ treating the content as Public Suffix List. # # See http://publicsuffix.org/format/ for more details about input format. # # @param string [#each_line] the list to parse # @param private_domains [Boolean] whether to ignore the private domains section # @return [PublicSuffix::List] def self.parse(input, private_domains: true) comment_token = "//".freeze private_token = "===BEGIN PRIVATE DOMAINS===".freeze section = nil # 1 == ICANN, 2 == PRIVATE new do |list| input.each_line do |line| line.strip! case # rubocop:disable Style/EmptyCaseCondition # skip blank lines when line.empty? next # include private domains or stop scanner when line.include?(private_token) break if !private_domains section = 2 # skip comments when line.start_with?(comment_token) next else list.add(Rule.factory(line, private: section == 2)) end end end end # Initializes an empty {PublicSuffix::List}. # # @yield [self] Yields on self. # @yieldparam [PublicSuffix::List] self The newly created instance. def initialize @rules = {} yield(self) if block_given? end # Checks whether two lists are equal. # # List <tt>one</tt> is equal to <tt>two</tt>, if <tt>two</tt> is an instance of # {PublicSuffix::List} and each +PublicSuffix::Rule::*+ # in list <tt>one</tt> is available in list <tt>two</tt>, in the same order. # # @param other [PublicSuffix::List] the List to compare # @return [Boolean] def ==(other) return false unless other.is_a?(List) equal?(other) || @rules == other.rules end alias eql? == # Iterates each rule in the list. def each(&block) Enumerator.new do |y| @rules.each do |key, node| y << entry_to_rule(node, key) end end.each(&block) end # Adds the given object to the list and optionally refreshes the rule index. # # @param rule [PublicSuffix::Rule::*] the rule to add to the list # @return [self] def add(rule) @rules[rule.value] = rule_to_entry(rule) self end alias << add # Gets the number of rules in the list. # # @return [Integer] def size @rules.size end # Checks whether the list is empty. # # @return [Boolean] def empty? @rules.empty? end # Removes all rules. # # @return [self] def clear @rules.clear self end # Finds and returns the rule corresponding to the longest public suffix for the hostname. # # @param name [#to_s] the hostname # @param default [PublicSuffix::Rule::*] the default rule to return in case no rule matches # @return [PublicSuffix::Rule::*] def find(name, default: default_rule, **options) rule = select(name, **options).inject do |l, r| return r if r.class == Rule::Exception l.length > r.length ? l : r end rule || default end # Selects all the rules matching given hostame. # # If `ignore_private` is set to true, the algorithm will skip the rules that are flagged as # private domain. Note that the rules will still be part of the loop. # If you frequently need to access lists ignoring the private domains, # you should create a list that doesn't include these domains setting the # `private_domains: false` option when calling {.parse}. # # Note that this method is currently private, as you should not rely on it. Instead, # the public interface is {#find}. The current internal algorithm allows to return all # matching rules, but different data structures may not be able to do it, and instead would # return only the match. For this reason, you should rely on {#find}. # # @param name [#to_s] the hostname # @param ignore_private [Boolean] # @return [Array<PublicSuffix::Rule::*>] def select(name, ignore_private: false) name = name.to_s parts = name.split(DOT).reverse! index = 0 query = parts[index] rules = [] loop do match = @rules[query] if !match.nil? && (ignore_private == false || match.private == false) rules << entry_to_rule(match, query) end index += 1 break if index >= parts.size query = parts[index] + DOT + query end rules end private :select # rubocop:disable Style/AccessModifierDeclarations # Gets the default rule. # # @see PublicSuffix::Rule.default_rule # # @return [PublicSuffix::Rule::*] def default_rule PublicSuffix::Rule.default end protected attr_reader :rules private def entry_to_rule(entry, value) entry.type.new(value: value, length: entry.length, private: entry.private) end def rule_to_entry(rule) Rule::Entry.new(rule.class, rule.length, rule.private) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/rule.rb
_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/lib/public_suffix/rule.rb
# = Public Suffix # # Domain name parser based on the Public Suffix List. # # Copyright (c) 2009-2018 Simone Carletti <weppos@weppos.net> module PublicSuffix # A Rule is a special object which holds a single definition # of the Public Suffix List. # # There are 3 types of rules, each one represented by a specific # subclass within the +PublicSuffix::Rule+ namespace. # # To create a new Rule, use the {PublicSuffix::Rule#factory} method. # # PublicSuffix::Rule.factory("ar") # # => #<PublicSuffix::Rule::Normal> # module Rule # @api internal Entry = Struct.new(:type, :length, :private) # = Abstract rule class # # This represent the base class for a Rule definition # in the {Public Suffix List}[https://publicsuffix.org]. # # This is intended to be an Abstract class # and you shouldn't create a direct instance. The only purpose # of this class is to expose a common interface # for all the available subclasses. # # * {PublicSuffix::Rule::Normal} # * {PublicSuffix::Rule::Exception} # * {PublicSuffix::Rule::Wildcard} # # ## Properties # # A rule is composed by 4 properties: # # value - A normalized version of the rule name. # The normalization process depends on rule tpe. # # Here's an example # # PublicSuffix::Rule.factory("*.google.com") # #<PublicSuffix::Rule::Wildcard:0x1015c14b0 # @value="google.com" # > # # ## Rule Creation # # The best way to create a new rule is passing the rule name # to the <tt>PublicSuffix::Rule.factory</tt> method. # # PublicSuffix::Rule.factory("com") # # => PublicSuffix::Rule::Normal # # PublicSuffix::Rule.factory("*.com") # # => PublicSuffix::Rule::Wildcard # # This method will detect the rule type and create an instance # from the proper rule class. # # ## Rule Usage # # A rule describes the composition of a domain name and explains how to tokenize # the name into tld, sld and trd. # # To use a rule, you first need to be sure the name you want to tokenize # can be handled by the current rule. # You can use the <tt>#match?</tt> method. # # rule = PublicSuffix::Rule.factory("com") # # rule.match?("google.com") # # => true # # rule.match?("google.com") # # => false # # Rule order is significant. A name can match more than one rule. # See the {Public Suffix Documentation}[http://publicsuffix.org/format/] # to learn more about rule priority. # # When you have the right rule, you can use it to tokenize the domain name. # # rule = PublicSuffix::Rule.factory("com") # # rule.decompose("google.com") # # => ["google", "com"] # # rule.decompose("www.google.com") # # => ["www.google", "com"] # # @abstract # class Base # @return [String] the rule definition attr_reader :value # @return [String] the length of the rule attr_reader :length # @return [Boolean] true if the rule is a private domain attr_reader :private # Initializes a new rule from the content. # # @param content [String] the content of the rule # @param private [Boolean] def self.build(content, private: false) new(value: content, private: private) end # Initializes a new rule. # # @param value [String] # @param private [Boolean] def initialize(value:, length: nil, private: false) @value = value.to_s @length = length || @value.count(DOT) + 1 @private = private end # Checks whether this rule is equal to <tt>other</tt>. # # @param [PublicSuffix::Rule::*] other The rule to compare # @return [Boolean] # Returns true if this rule and other are instances of the same class # and has the same value, false otherwise. def ==(other) equal?(other) || (self.class == other.class && value == other.value) end alias eql? == # Checks if this rule matches +name+. # # A domain name is said to match a rule if and only if # all of the following conditions are met: # # - When the domain and rule are split into corresponding labels, # that the domain contains as many or more labels than the rule. # - Beginning with the right-most labels of both the domain and the rule, # and continuing for all labels in the rule, one finds that for every pair, # either they are identical, or that the label from the rule is "*". # # @see https://publicsuffix.org/list/ # # @example # PublicSuffix::Rule.factory("com").match?("example.com") # # => true # PublicSuffix::Rule.factory("com").match?("example.net") # # => false # # @param name [String] the domain name to check # @return [Boolean] def match?(name) # Note: it works because of the assumption there are no # rules like foo.*.com. If the assumption is incorrect, # we need to properly walk the input and skip parts according # to wildcard component. diff = name.chomp(value) diff.empty? || diff.end_with?(DOT) end # @abstract def parts raise NotImplementedError end # @abstract # @param [String, #to_s] name The domain name to decompose # @return [Array<String, nil>] def decompose(*) raise NotImplementedError end end # Normal represents a standard rule (e.g. com). class Normal < Base # Gets the original rule definition. # # @return [String] The rule definition. def rule value end # Decomposes the domain name according to rule properties. # # @param [String, #to_s] name The domain name to decompose # @return [Array<String>] The array with [trd + sld, tld]. def decompose(domain) suffix = parts.join('\.') matches = domain.to_s.match(/^(.*)\.(#{suffix})$/) matches ? matches[1..2] : [nil, nil] end # dot-split rule value and returns all rule parts # in the order they appear in the value. # # @return [Array<String>] def parts @value.split(DOT) end end # Wildcard represents a wildcard rule (e.g. *.co.uk). class Wildcard < Base # Initializes a new rule from the content. # # @param content [String] the content of the rule # @param private [Boolean] def self.build(content, private: false) new(value: content.to_s[2..-1], private: private) end # Initializes a new rule. # # @param value [String] # @param private [Boolean] def initialize(value:, length: nil, private: false) super(value: value, length: length, private: private) length or @length += 1 # * counts as 1 end # Gets the original rule definition. # # @return [String] The rule definition. def rule value == "" ? STAR : STAR + DOT + value end # Decomposes the domain name according to rule properties. # # @param [String, #to_s] name The domain name to decompose # @return [Array<String>] The array with [trd + sld, tld]. def decompose(domain) suffix = ([".*?"] + parts).join('\.') matches = domain.to_s.match(/^(.*)\.(#{suffix})$/) matches ? matches[1..2] : [nil, nil] end # dot-split rule value and returns all rule parts # in the order they appear in the value. # # @return [Array<String>] def parts @value.split(DOT) end end # Exception represents an exception rule (e.g. !parliament.uk). class Exception < Base # Initializes a new rule from the content. # # @param content [String] the content of the rule # @param private [Boolean] def self.build(content, private: false) new(value: content.to_s[1..-1], private: private) end # Gets the original rule definition. # # @return [String] The rule definition. def rule BANG + value end # Decomposes the domain name according to rule properties. # # @param [String, #to_s] name The domain name to decompose # @return [Array<String>] The array with [trd + sld, tld]. def decompose(domain) suffix = parts.join('\.') matches = domain.to_s.match(/^(.*)\.(#{suffix})$/) matches ? matches[1..2] : [nil, nil] end # dot-split rule value and returns all rule parts # in the order they appear in the value. # The leftmost label is not considered a label. # # See http://publicsuffix.org/format/: # If the prevailing rule is a exception rule, # modify it by removing the leftmost label. # # @return [Array<String>] def parts @value.split(DOT)[1..-1] end end # Takes the +name+ of the rule, detects the specific rule class # and creates a new instance of that class. # The +name+ becomes the rule +value+. # # @example Creates a Normal rule # PublicSuffix::Rule.factory("ar") # # => #<PublicSuffix::Rule::Normal> # # @example Creates a Wildcard rule # PublicSuffix::Rule.factory("*.ar") # # => #<PublicSuffix::Rule::Wildcard> # # @example Creates an Exception rule # PublicSuffix::Rule.factory("!congresodelalengua3.ar") # # => #<PublicSuffix::Rule::Exception> # # @param [String] content The rule content. # @return [PublicSuffix::Rule::*] A rule instance. def self.factory(content, private: false) case content.to_s[0, 1] when STAR Wildcard when BANG Exception else Normal end.build(content, private: private) end # The default rule to use if no rule match. # # The default rule is "*". From https://publicsuffix.org/list/: # # > If no rules match, the prevailing rule is "*". # # @return [PublicSuffix::Rule::Wildcard] The default rule. def self.default factory(STAR) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/trollop-2.1.2/test/test_helper.rb
_vendor/ruby/2.6.0/gems/trollop-2.1.2/test/test_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) unless ENV['MUTANT'] begin require "coveralls" Coveralls.wear! rescue LoadError end end begin require "pry" rescue LoadError end require 'minitest/autorun' require 'trollop'
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/trollop-2.1.2/test/test_trollop.rb
_vendor/ruby/2.6.0/gems/trollop-2.1.2/test/test_trollop.rb
require 'stringio' require 'test_helper' module Trollop module Test class Trollop < ::MiniTest::Unit::TestCase def setup @p = Parser.new end def test_die_without_options_ever_run ::Trollop.send(:instance_variable_set, "@last_parser", nil) assert_raises(ArgumentError) { ::Trollop.die 'hello' } end def test_unknown_arguments assert_raises(CommandlineError) { @p.parse(%w(--arg)) } @p.opt "arg" @p.parse(%w(--arg)) assert_raises(CommandlineError) { @p.parse(%w(--arg2)) } end def test_syntax_check @p.opt "arg" @p.parse(%w(--arg)) @p.parse(%w(arg)) assert_raises(CommandlineError) { @p.parse(%w(---arg)) } assert_raises(CommandlineError) { @p.parse(%w(-arg)) } end def test_required_flags_are_required @p.opt "arg", "desc", :required => true @p.opt "arg2", "desc", :required => false @p.opt "arg3", "desc", :required => false @p.parse(%w(--arg)) @p.parse(%w(--arg --arg2)) assert_raises(CommandlineError) { @p.parse(%w(--arg2)) } assert_raises(CommandlineError) { @p.parse(%w(--arg2 --arg3)) } end ## flags that take an argument error unless given one def test_argflags_demand_args @p.opt "goodarg", "desc", :type => String @p.opt "goodarg2", "desc", :type => String @p.parse(%w(--goodarg goat)) assert_raises(CommandlineError) { @p.parse(%w(--goodarg --goodarg2 goat)) } assert_raises(CommandlineError) { @p.parse(%w(--goodarg)) } end ## flags that don't take arguments ignore them def test_arglessflags_refuse_args @p.opt "goodarg" @p.opt "goodarg2" @p.parse(%w(--goodarg)) @p.parse(%w(--goodarg --goodarg2)) opts = @p.parse %w(--goodarg a) assert_equal true, opts["goodarg"] assert_equal ["a"], @p.leftovers end ## flags that require args of a specific type refuse args of other ## types def test_typed_args_refuse_args_of_other_types @p.opt "goodarg", "desc", :type => :int assert_raises(ArgumentError) { @p.opt "badarg", "desc", :type => :asdf } @p.parse(%w(--goodarg 3)) assert_raises(CommandlineError) { @p.parse(%w(--goodarg 4.2)) } assert_raises(CommandlineError) { @p.parse(%w(--goodarg hello)) } end ## type is correctly derived from :default def test_type_correctly_derived_from_default assert_raises(ArgumentError) { @p.opt "badarg", "desc", :default => [] } assert_raises(ArgumentError) { @p.opt "badarg3", "desc", :default => [{1 => 2}] } assert_raises(ArgumentError) { @p.opt "badarg4", "desc", :default => Hash.new } # single arg: int @p.opt "argsi", "desc", :default => 0 opts = @p.parse(%w(--)) assert_equal 0, opts["argsi"] opts = @p.parse(%w(--argsi 4)) assert_equal 4, opts["argsi"] opts = @p.parse(%w(--argsi=4)) assert_equal 4, opts["argsi"] opts = @p.parse(%w(--argsi=-4)) assert_equal -4, opts["argsi"] assert_raises(CommandlineError) { @p.parse(%w(--argsi 4.2)) } assert_raises(CommandlineError) { @p.parse(%w(--argsi hello)) } # single arg: float @p.opt "argsf", "desc", :default => 3.14 opts = @p.parse(%w(--)) assert_equal 3.14, opts["argsf"] opts = @p.parse(%w(--argsf 2.41)) assert_equal 2.41, opts["argsf"] opts = @p.parse(%w(--argsf 2)) assert_equal 2, opts["argsf"] opts = @p.parse(%w(--argsf 1.0e-2)) assert_equal 1.0e-2, opts["argsf"] assert_raises(CommandlineError) { @p.parse(%w(--argsf hello)) } # single arg: date date = Date.today @p.opt "argsd", "desc", :default => date opts = @p.parse(%w(--)) assert_equal Date.today, opts["argsd"] opts = @p.parse(['--argsd', 'Jan 4, 2007']) assert_equal Date.civil(2007, 1, 4), opts["argsd"] assert_raises(CommandlineError) { @p.parse(%w(--argsd hello)) } # single arg: string @p.opt "argss", "desc", :default => "foobar" opts = @p.parse(%w(--)) assert_equal "foobar", opts["argss"] opts = @p.parse(%w(--argss 2.41)) assert_equal "2.41", opts["argss"] opts = @p.parse(%w(--argss hello)) assert_equal "hello", opts["argss"] # multi args: ints @p.opt "argmi", "desc", :default => [3, 5] opts = @p.parse(%w(--)) assert_equal [3, 5], opts["argmi"] opts = @p.parse(%w(--argmi 4)) assert_equal [4], opts["argmi"] assert_raises(CommandlineError) { @p.parse(%w(--argmi 4.2)) } assert_raises(CommandlineError) { @p.parse(%w(--argmi hello)) } # multi args: floats @p.opt "argmf", "desc", :default => [3.34, 5.21] opts = @p.parse(%w(--)) assert_equal [3.34, 5.21], opts["argmf"] opts = @p.parse(%w(--argmf 2)) assert_equal [2], opts["argmf"] opts = @p.parse(%w(--argmf 4.0)) assert_equal [4.0], opts["argmf"] assert_raises(CommandlineError) { @p.parse(%w(--argmf hello)) } # multi args: dates dates = [Date.today, Date.civil(2007, 1, 4)] @p.opt "argmd", "desc", :default => dates opts = @p.parse(%w(--)) assert_equal dates, opts["argmd"] opts = @p.parse(['--argmd', 'Jan 4, 2007']) assert_equal [Date.civil(2007, 1, 4)], opts["argmd"] assert_raises(CommandlineError) { @p.parse(%w(--argmd hello)) } # multi args: strings @p.opt "argmst", "desc", :default => %w(hello world) opts = @p.parse(%w(--)) assert_equal %w(hello world), opts["argmst"] opts = @p.parse(%w(--argmst 3.4)) assert_equal ["3.4"], opts["argmst"] opts = @p.parse(%w(--argmst goodbye)) assert_equal ["goodbye"], opts["argmst"] end ## :type and :default must match if both are specified def test_type_and_default_must_match assert_raises(ArgumentError) { @p.opt "badarg", "desc", :type => :int, :default => "hello" } assert_raises(ArgumentError) { @p.opt "badarg2", "desc", :type => :String, :default => 4 } assert_raises(ArgumentError) { @p.opt "badarg2", "desc", :type => :String, :default => ["hi"] } assert_raises(ArgumentError) { @p.opt "badarg2", "desc", :type => :ints, :default => [3.14] } @p.opt "argsi", "desc", :type => :int, :default => 4 @p.opt "argsf", "desc", :type => :float, :default => 3.14 @p.opt "argsd", "desc", :type => :date, :default => Date.today @p.opt "argss", "desc", :type => :string, :default => "yo" @p.opt "argmi", "desc", :type => :ints, :default => [4] @p.opt "argmf", "desc", :type => :floats, :default => [3.14] @p.opt "argmd", "desc", :type => :dates, :default => [Date.today] @p.opt "argmst", "desc", :type => :strings, :default => ["yo"] end ## def test_flags_with_defaults_and_no_args_act_as_switches @p.opt :argd, "desc", :default => "default_string" opts = @p.parse(%w(--)) assert !opts[:argd_given] assert_equal "default_string", opts[:argd] opts = @p.parse(%w( --argd )) assert opts[:argd_given] assert_equal "default_string", opts[:argd] opts = @p.parse(%w(--argd different_string)) assert opts[:argd_given] assert_equal "different_string", opts[:argd] end def test_flag_with_no_defaults_and_no_args_act_as_switches_array opts = nil @p.opt :argd, "desc", :type => :strings, :default => ["default_string"] opts = @p.parse(%w(--argd)) assert_equal ["default_string"], opts[:argd] end def test_type_and_empty_array @p.opt "argmi", "desc", :type => :ints, :default => [] @p.opt "argmf", "desc", :type => :floats, :default => [] @p.opt "argmd", "desc", :type => :dates, :default => [] @p.opt "argms", "desc", :type => :strings, :default => [] assert_raises(ArgumentError) { @p.opt "badi", "desc", :type => :int, :default => [] } assert_raises(ArgumentError) { @p.opt "badf", "desc", :type => :float, :default => [] } assert_raises(ArgumentError) { @p.opt "badd", "desc", :type => :date, :default => [] } assert_raises(ArgumentError) { @p.opt "bads", "desc", :type => :string, :default => [] } opts = @p.parse([]) assert_equal(opts["argmi"], []) assert_equal(opts["argmf"], []) assert_equal(opts["argmd"], []) assert_equal(opts["argms"], []) end def test_long_detects_bad_names @p.opt "goodarg", "desc", :long => "none" @p.opt "goodarg2", "desc", :long => "--two" assert_raises(ArgumentError) { @p.opt "badarg", "desc", :long => "" } assert_raises(ArgumentError) { @p.opt "badarg2", "desc", :long => "--" } assert_raises(ArgumentError) { @p.opt "badarg3", "desc", :long => "-one" } assert_raises(ArgumentError) { @p.opt "badarg4", "desc", :long => "---toomany" } end def test_short_detects_bad_names @p.opt "goodarg", "desc", :short => "a" @p.opt "goodarg2", "desc", :short => "-b" assert_raises(ArgumentError) { @p.opt "badarg", "desc", :short => "" } assert_raises(ArgumentError) { @p.opt "badarg2", "desc", :short => "-ab" } assert_raises(ArgumentError) { @p.opt "badarg3", "desc", :short => "--t" } end def test_short_names_created_automatically @p.opt "arg" @p.opt "arg2" @p.opt "arg3" opts = @p.parse %w(-a -g) assert_equal true, opts["arg"] assert_equal false, opts["arg2"] assert_equal true, opts["arg3"] end def test_short_autocreation_skips_dashes_and_numbers @p.opt :arg # auto: a @p.opt :arg_potato # auto: r @p.opt :arg_muffin # auto: g @p.opt :arg_daisy # auto: d (not _)! @p.opt :arg_r2d2f # auto: f (not 2)! opts = @p.parse %w(-f -d) assert_equal true, opts[:arg_daisy] assert_equal true, opts[:arg_r2d2f] assert_equal false, opts[:arg] assert_equal false, opts[:arg_potato] assert_equal false, opts[:arg_muffin] end def test_short_autocreation_is_ok_with_running_out_of_chars @p.opt :arg1 # auto: a @p.opt :arg2 # auto: r @p.opt :arg3 # auto: g @p.opt :arg4 # auto: uh oh! @p.parse [] end def test_short_can_be_nothing @p.opt "arg", "desc", :short => :none @p.parse [] sio = StringIO.new "w" @p.educate sio assert sio.string =~ /--arg\s+desc/ assert_raises(CommandlineError) { @p.parse %w(-a) } end ## two args can't have the same name def test_conflicting_names_are_detected @p.opt "goodarg" assert_raises(ArgumentError) { @p.opt "goodarg" } end ## two args can't have the same :long def test_conflicting_longs_detected @p.opt "goodarg", "desc", :long => "--goodarg" assert_raises(ArgumentError) { @p.opt "badarg", "desc", :long => "--goodarg" } end ## two args can't have the same :short def test_conflicting_shorts_detected @p.opt "goodarg", "desc", :short => "-g" assert_raises(ArgumentError) { @p.opt "badarg", "desc", :short => "-g" } end ## note: this behavior has changed in trollop 2.0! def test_flag_parameters @p.opt :defaultnone, "desc" @p.opt :defaultfalse, "desc", :default => false @p.opt :defaulttrue, "desc", :default => true ## default state opts = @p.parse [] assert_equal false, opts[:defaultnone] assert_equal false, opts[:defaultfalse] assert_equal true, opts[:defaulttrue] ## specifying turns them on, regardless of default opts = @p.parse %w(--defaultfalse --defaulttrue --defaultnone) assert_equal true, opts[:defaultnone] assert_equal true, opts[:defaultfalse] assert_equal true, opts[:defaulttrue] ## using --no- form turns them off, regardless of default opts = @p.parse %w(--no-defaultfalse --no-defaulttrue --no-defaultnone) assert_equal false, opts[:defaultnone] assert_equal false, opts[:defaultfalse] assert_equal false, opts[:defaulttrue] end ## note: this behavior has changed in trollop 2.0! def test_flag_parameters_for_inverted_flags @p.opt :no_default_none, "desc" @p.opt :no_default_false, "desc", :default => false @p.opt :no_default_true, "desc", :default => true ## default state opts = @p.parse [] assert_equal false, opts[:no_default_none] assert_equal false, opts[:no_default_false] assert_equal true, opts[:no_default_true] ## specifying turns them all on, regardless of default opts = @p.parse %w(--no-default-false --no-default-true --no-default-none) p opts assert_equal true, opts[:no_default_none] assert_equal true, opts[:no_default_false] assert_equal true, opts[:no_default_true] ## using dropped-no form turns them all off, regardless of default opts = @p.parse %w(--default-false --default-true --default-none) assert_equal false, opts[:no_default_none] assert_equal false, opts[:no_default_false] assert_equal false, opts[:no_default_true] ## disallow double negatives for reasons of sanity preservation assert_raises(CommandlineError) { @p.parse %w(--no-no-default-true) } end def test_special_flags_work @p.version "asdf fdas" assert_raises(VersionNeeded) { @p.parse(%w(-v)) } assert_raises(HelpNeeded) { @p.parse(%w(-h)) } end def test_short_options_combine @p.opt :arg1, "desc", :short => "a" @p.opt :arg2, "desc", :short => "b" @p.opt :arg3, "desc", :short => "c", :type => :int opts = @p.parse %w(-a -b) assert_equal true, opts[:arg1] assert_equal true, opts[:arg2] assert_equal nil, opts[:arg3] opts = @p.parse %w(-ab) assert_equal true, opts[:arg1] assert_equal true, opts[:arg2] assert_equal nil, opts[:arg3] opts = @p.parse %w(-ac 4 -b) assert_equal true, opts[:arg1] assert_equal true, opts[:arg2] assert_equal 4, opts[:arg3] assert_raises(CommandlineError) { @p.parse %w(-cab 4) } assert_raises(CommandlineError) { @p.parse %w(-cba 4) } end def test_version_only_appears_if_set @p.opt "arg" assert_raises(CommandlineError) { @p.parse %w(-v) } @p.version "trollop 1.2.3.4" assert_raises(VersionNeeded) { @p.parse %w(-v) } end def test_doubledash_ends_option_processing @p.opt :arg1, "desc", :short => "a", :default => 0 @p.opt :arg2, "desc", :short => "b", :default => 0 opts = @p.parse %w(-- -a 3 -b 2) assert_equal opts[:arg1], 0 assert_equal opts[:arg2], 0 assert_equal %w(-a 3 -b 2), @p.leftovers opts = @p.parse %w(-a 3 -- -b 2) assert_equal opts[:arg1], 3 assert_equal opts[:arg2], 0 assert_equal %w(-b 2), @p.leftovers opts = @p.parse %w(-a 3 -b 2 --) assert_equal opts[:arg1], 3 assert_equal opts[:arg2], 2 assert_equal %w(), @p.leftovers end def test_wrap assert_equal [""], @p.wrap("") assert_equal ["a"], @p.wrap("a") assert_equal ["one two", "three"], @p.wrap("one two three", :width => 8) assert_equal ["one two three"], @p.wrap("one two three", :width => 80) assert_equal ["one", "two", "three"], @p.wrap("one two three", :width => 3) assert_equal ["onetwothree"], @p.wrap("onetwothree", :width => 3) assert_equal [ "Test is an awesome program that does something very, very important.", "", "Usage:", " test [options] <filenames>+", "where [options] are:"], @p.wrap(<<EOM, :width => 100) Test is an awesome program that does something very, very important. Usage: test [options] <filenames>+ where [options] are: EOM end def test_multi_line_description out = StringIO.new @p.opt :arg, <<-EOM, :type => :int This is an arg with a multi-line description EOM @p.educate(out) assert_equal <<-EOM, out.string Options: --arg=<i> This is an arg with a multi-line description EOM end def test_floating_point_formatting @p.opt :arg, "desc", :type => :float, :short => "f" opts = @p.parse %w(-f 1) assert_equal 1.0, opts[:arg] opts = @p.parse %w(-f 1.0) assert_equal 1.0, opts[:arg] opts = @p.parse %w(-f 0.1) assert_equal 0.1, opts[:arg] opts = @p.parse %w(-f .1) assert_equal 0.1, opts[:arg] opts = @p.parse %w(-f .99999999999999999999) assert_equal 1.0, opts[:arg] opts = @p.parse %w(-f -1) assert_equal(-1.0, opts[:arg]) opts = @p.parse %w(-f -1.0) assert_equal(-1.0, opts[:arg]) opts = @p.parse %w(-f -0.1) assert_equal(-0.1, opts[:arg]) opts = @p.parse %w(-f -.1) assert_equal(-0.1, opts[:arg]) assert_raises(CommandlineError) { @p.parse %w(-f a) } assert_raises(CommandlineError) { @p.parse %w(-f 1a) } assert_raises(CommandlineError) { @p.parse %w(-f 1.a) } assert_raises(CommandlineError) { @p.parse %w(-f a.1) } assert_raises(CommandlineError) { @p.parse %w(-f 1.0.0) } assert_raises(CommandlineError) { @p.parse %w(-f .) } assert_raises(CommandlineError) { @p.parse %w(-f -.) } end def test_date_formatting @p.opt :arg, "desc", :type => :date, :short => 'd' opts = @p.parse(['-d', 'Jan 4, 2007']) assert_equal Date.civil(2007, 1, 4), opts[:arg] opts = @p.parse(['-d', 'today']) assert_equal Date.today, opts[:arg] end def test_short_options_cant_be_numeric assert_raises(ArgumentError) { @p.opt :arg, "desc", :short => "-1" } @p.opt :a1b, "desc" @p.opt :a2b, "desc" assert @p.specs[:a2b][:short].to_i == 0 end def test_short_options_can_be_weird @p.opt :arg1, "desc", :short => "#" @p.opt :arg2, "desc", :short => "." assert_raises(ArgumentError) { @p.opt :arg3, "desc", :short => "-" } end def test_options_cant_be_set_multiple_times_if_not_specified @p.opt :arg, "desc", :short => "-x" @p.parse %w(-x) assert_raises(CommandlineError) { @p.parse %w(-x -x) } assert_raises(CommandlineError) { @p.parse %w(-xx) } end def test_options_can_be_set_multiple_times_if_specified @p.opt :arg, "desc", :short => "-x", :multi => true @p.parse %w(-x) @p.parse %w(-x -x) @p.parse %w(-xx) end def test_short_options_with_multiple_options @p.opt :xarg, "desc", :short => "-x", :type => String, :multi => true opts = @p.parse %w(-x a -x b) assert_equal %w(a b), opts[:xarg] assert_equal [], @p.leftovers end def test_short_options_with_multiple_options_does_not_affect_flags_type @p.opt :xarg, "desc", :short => "-x", :type => :flag, :multi => true opts = @p.parse %w(-x a) assert_equal true, opts[:xarg] assert_equal %w(a), @p.leftovers opts = @p.parse %w(-x a -x b) assert_equal true, opts[:xarg] assert_equal %w(a b), @p.leftovers opts = @p.parse %w(-xx a -x b) assert_equal true, opts[:xarg] assert_equal %w(a b), @p.leftovers end def test_short_options_with_multiple_arguments @p.opt :xarg, "desc", :type => :ints opts = @p.parse %w(-x 3 4 0) assert_equal [3, 4, 0], opts[:xarg] assert_equal [], @p.leftovers @p.opt :yarg, "desc", :type => :floats opts = @p.parse %w(-y 3.14 4.21 0.66) assert_equal [3.14, 4.21, 0.66], opts[:yarg] assert_equal [], @p.leftovers @p.opt :zarg, "desc", :type => :strings opts = @p.parse %w(-z a b c) assert_equal %w(a b c), opts[:zarg] assert_equal [], @p.leftovers end def test_short_options_with_multiple_options_and_arguments @p.opt :xarg, "desc", :type => :ints, :multi => true opts = @p.parse %w(-x 3 4 5 -x 6 7) assert_equal [[3, 4, 5], [6, 7]], opts[:xarg] assert_equal [], @p.leftovers @p.opt :yarg, "desc", :type => :floats, :multi => true opts = @p.parse %w(-y 3.14 4.21 5.66 -y 6.99 7.01) assert_equal [[3.14, 4.21, 5.66], [6.99, 7.01]], opts[:yarg] assert_equal [], @p.leftovers @p.opt :zarg, "desc", :type => :strings, :multi => true opts = @p.parse %w(-z a b c -z d e) assert_equal [%w(a b c), %w(d e)], opts[:zarg] assert_equal [], @p.leftovers end def test_combined_short_options_with_multiple_arguments @p.opt :arg1, "desc", :short => "a" @p.opt :arg2, "desc", :short => "b" @p.opt :arg3, "desc", :short => "c", :type => :ints @p.opt :arg4, "desc", :short => "d", :type => :floats opts = @p.parse %w(-abc 4 6 9) assert_equal true, opts[:arg1] assert_equal true, opts[:arg2] assert_equal [4, 6, 9], opts[:arg3] opts = @p.parse %w(-ac 4 6 9 -bd 3.14 2.41) assert_equal true, opts[:arg1] assert_equal true, opts[:arg2] assert_equal [4, 6, 9], opts[:arg3] assert_equal [3.14, 2.41], opts[:arg4] assert_raises(CommandlineError) { opts = @p.parse %w(-abcd 3.14 2.41) } end def test_long_options_with_multiple_options @p.opt :xarg, "desc", :type => String, :multi => true opts = @p.parse %w(--xarg=a --xarg=b) assert_equal %w(a b), opts[:xarg] assert_equal [], @p.leftovers opts = @p.parse %w(--xarg a --xarg b) assert_equal %w(a b), opts[:xarg] assert_equal [], @p.leftovers end def test_long_options_with_multiple_arguments @p.opt :xarg, "desc", :type => :ints opts = @p.parse %w(--xarg 3 2 5) assert_equal [3, 2, 5], opts[:xarg] assert_equal [], @p.leftovers opts = @p.parse %w(--xarg=3) assert_equal [3], opts[:xarg] assert_equal [], @p.leftovers @p.opt :yarg, "desc", :type => :floats opts = @p.parse %w(--yarg 3.14 2.41 5.66) assert_equal [3.14, 2.41, 5.66], opts[:yarg] assert_equal [], @p.leftovers opts = @p.parse %w(--yarg=3.14) assert_equal [3.14], opts[:yarg] assert_equal [], @p.leftovers @p.opt :zarg, "desc", :type => :strings opts = @p.parse %w(--zarg a b c) assert_equal %w(a b c), opts[:zarg] assert_equal [], @p.leftovers opts = @p.parse %w(--zarg=a) assert_equal %w(a), opts[:zarg] assert_equal [], @p.leftovers end def test_long_options_with_multiple_options_and_arguments @p.opt :xarg, "desc", :type => :ints, :multi => true opts = @p.parse %w(--xarg 3 2 5 --xarg 2 1) assert_equal [[3, 2, 5], [2, 1]], opts[:xarg] assert_equal [], @p.leftovers opts = @p.parse %w(--xarg=3 --xarg=2) assert_equal [[3], [2]], opts[:xarg] assert_equal [], @p.leftovers @p.opt :yarg, "desc", :type => :floats, :multi => true opts = @p.parse %w(--yarg 3.14 2.72 5 --yarg 2.41 1.41) assert_equal [[3.14, 2.72, 5], [2.41, 1.41]], opts[:yarg] assert_equal [], @p.leftovers opts = @p.parse %w(--yarg=3.14 --yarg=2.41) assert_equal [[3.14], [2.41]], opts[:yarg] assert_equal [], @p.leftovers @p.opt :zarg, "desc", :type => :strings, :multi => true opts = @p.parse %w(--zarg a b c --zarg d e) assert_equal [%w(a b c), %w(d e)], opts[:zarg] assert_equal [], @p.leftovers opts = @p.parse %w(--zarg=a --zarg=d) assert_equal [%w(a), %w(d)], opts[:zarg] assert_equal [], @p.leftovers end def test_long_options_also_take_equals @p.opt :arg, "desc", :long => "arg", :type => String, :default => "hello" opts = @p.parse %w() assert_equal "hello", opts[:arg] opts = @p.parse %w(--arg goat) assert_equal "goat", opts[:arg] opts = @p.parse %w(--arg=goat) assert_equal "goat", opts[:arg] ## actually, this next one is valid. empty string for --arg, and goat as a ## leftover. ## assert_raises(CommandlineError) { opts = @p.parse %w(--arg= goat) } end def test_auto_generated_long_names_convert_underscores_to_hyphens @p.opt :hello_there assert_equal "hello-there", @p.specs[:hello_there][:long] end def test_arguments_passed_through_block @goat = 3 boat = 4 Parser.new(@goat) do |goat| boat = goat end assert_equal @goat, boat end def test_help_has_default_banner @p = Parser.new sio = StringIO.new "w" @p.parse [] @p.educate sio help = sio.string.split "\n" assert help[0] =~ /options/i assert_equal 2, help.length # options, then -h @p = Parser.new @p.version "my version" sio = StringIO.new "w" @p.parse [] @p.educate sio help = sio.string.split "\n" assert help[0] =~ /my version/i assert_equal 4, help.length # version, options, -h, -v @p = Parser.new @p.banner "my own banner" sio = StringIO.new "w" @p.parse [] @p.educate sio help = sio.string.split "\n" assert help[0] =~ /my own banner/i assert_equal 2, help.length # banner, -h end def test_help_has_optional_usage @p = Parser.new @p.usage "OPTIONS FILES" sio = StringIO.new "w" @p.parse [] @p.educate sio help = sio.string.split "\n" assert help[0] =~ /OPTIONS FILES/i assert_equal 4, help.length # line break, options, then -h end def test_help_has_optional_synopsis @p = Parser.new @p.synopsis "About this program" sio = StringIO.new "w" @p.parse [] @p.educate sio help = sio.string.split "\n" assert help[0] =~ /About this program/i assert_equal 4, help.length # line break, options, then -h end def test_help_has_specific_order_for_usage_and_synopsis @p = Parser.new @p.usage "OPTIONS FILES" @p.synopsis "About this program" sio = StringIO.new "w" @p.parse [] @p.educate sio help = sio.string.split "\n" assert help[0] =~ /OPTIONS FILES/i assert help[1] =~ /About this program/i assert_equal 5, help.length # line break, options, then -h end def test_help_preserves_positions @p.opt :zzz, "zzz" @p.opt :aaa, "aaa" sio = StringIO.new "w" @p.educate sio help = sio.string.split "\n" assert help[1] =~ /zzz/ assert help[2] =~ /aaa/ end def test_help_includes_option_types @p.opt :arg1, 'arg', :type => :int @p.opt :arg2, 'arg', :type => :ints @p.opt :arg3, 'arg', :type => :string @p.opt :arg4, 'arg', :type => :strings @p.opt :arg5, 'arg', :type => :float @p.opt :arg6, 'arg', :type => :floats @p.opt :arg7, 'arg', :type => :io @p.opt :arg8, 'arg', :type => :ios @p.opt :arg9, 'arg', :type => :date @p.opt :arg10, 'arg', :type => :dates sio = StringIO.new "w" @p.educate sio help = sio.string.split "\n" assert help[1] =~ /<i>/ assert help[2] =~ /<i\+>/ assert help[3] =~ /<s>/ assert help[4] =~ /<s\+>/ assert help[5] =~ /<f>/ assert help[6] =~ /<f\+>/ assert help[7] =~ /<filename\/uri>/ assert help[8] =~ /<filename\/uri\+>/ assert help[9] =~ /<date>/ assert help[10] =~ /<date\+>/ end def test_help_has_grammatical_default_text @p.opt :arg1, 'description with period.', :default => 'hello' @p.opt :arg2, 'description without period', :default => 'world' sio = StringIO.new 'w' @p.educate sio help = sio.string.split "\n" assert help[1] =~ /Default/ assert help[2] =~ /default/ end def test_version_and_help_short_args_can_be_overridden @p.opt :verbose, "desc", :short => "-v" @p.opt :hello, "desc", :short => "-h" @p.version "version" @p.parse(%w(-v)) assert_raises(VersionNeeded) { @p.parse(%w(--version)) } @p.parse(%w(-h)) assert_raises(HelpNeeded) { @p.parse(%w(--help)) } end def test_version_and_help_long_args_can_be_overridden @p.opt :asdf, "desc", :long => "help" @p.opt :asdf2, "desc2", :long => "version" @p.parse %w() @p.parse %w(--help) @p.parse %w(--version) @p.parse %w(-h) @p.parse %w(-v) end def test_version_and_help_override_errors @p.opt :asdf, "desc", :type => String @p.version "version" @p.parse %w(--asdf goat) assert_raises(CommandlineError) { @p.parse %w(--asdf) } assert_raises(HelpNeeded) { @p.parse %w(--asdf --help) } assert_raises(VersionNeeded) { @p.parse %w(--asdf --version) } end def test_conflicts @p.opt :one assert_raises(ArgumentError) { @p.conflicts :one, :two } @p.opt :two @p.conflicts :one, :two @p.parse %w(--one) @p.parse %w(--two) assert_raises(CommandlineError) { @p.parse %w(--one --two) } @p.opt :hello @p.opt :yellow @p.opt :mellow @p.opt :jello @p.conflicts :hello, :yellow, :mellow, :jello assert_raises(CommandlineError) { @p.parse %w(--hello --yellow --mellow --jello) } assert_raises(CommandlineError) { @p.parse %w(--hello --mellow --jello) } assert_raises(CommandlineError) { @p.parse %w(--hello --jello) } @p.parse %w(--hello) @p.parse %w(--jello) @p.parse %w(--yellow) @p.parse %w(--mellow) @p.parse %w(--mellow --one) @p.parse %w(--mellow --two) assert_raises(CommandlineError) { @p.parse %w(--mellow --two --jello) } assert_raises(CommandlineError) { @p.parse %w(--one --mellow --two --jello) } end def test_conflict_error_messages @p.opt :one @p.opt "two" @p.conflicts :one, "two" assert_raises(CommandlineError, /--one.*--two/) { @p.parse %w(--one --two) } end def test_depends @p.opt :one assert_raises(ArgumentError) { @p.depends :one, :two } @p.opt :two @p.depends :one, :two @p.parse %w(--one --two) assert_raises(CommandlineError) { @p.parse %w(--one) } assert_raises(CommandlineError) { @p.parse %w(--two) } @p.opt :hello @p.opt :yellow @p.opt :mellow @p.opt :jello @p.depends :hello, :yellow, :mellow, :jello @p.parse %w(--hello --yellow --mellow --jello) assert_raises(CommandlineError) { @p.parse %w(--hello --mellow --jello) } assert_raises(CommandlineError) { @p.parse %w(--hello --jello) } assert_raises(CommandlineError) { @p.parse %w(--hello) } assert_raises(CommandlineError) { @p.parse %w(--mellow) } @p.parse %w(--hello --yellow --mellow --jello --one --two) @p.parse %w(--hello --yellow --mellow --jello --one --two a b c) assert_raises(CommandlineError) { @p.parse %w(--mellow --two --jello --one) } end def test_depend_error_messages @p.opt :one @p.opt "two" @p.depends :one, "two" @p.parse %w(--one --two) assert_raises(CommandlineError, /--one.*--two/) { @p.parse %w(--one) } assert_raises(CommandlineError, /--one.*--two/) { @p.parse %w(--two) } end ## courtesy neill zero def test_two_required_one_missing_accuses_correctly @p.opt "arg1", "desc1", :required => true @p.opt "arg2", "desc2", :required => true assert_raises(CommandlineError, /arg2/) { @p.parse(%w(--arg1)) } assert_raises(CommandlineError, /arg1/) { @p.parse(%w(--arg2)) } @p.parse(%w(--arg1 --arg2)) end def test_stopwords_mixed @p.opt "arg1", :default => false @p.opt "arg2", :default => false @p.stop_on %w(happy sad) opts = @p.parse %w(--arg1 happy --arg2) assert_equal true, opts["arg1"] assert_equal false, opts["arg2"] ## restart parsing @p.leftovers.shift opts = @p.parse @p.leftovers assert_equal false, opts["arg1"] assert_equal true, opts["arg2"] end def test_stopwords_no_stopwords @p.opt "arg1", :default => false @p.opt "arg2", :default => false @p.stop_on %w(happy sad) opts = @p.parse %w(--arg1 --arg2) assert_equal true, opts["arg1"] assert_equal true, opts["arg2"] ## restart parsing @p.leftovers.shift opts = @p.parse @p.leftovers assert_equal false, opts["arg1"] assert_equal false, opts["arg2"] end def test_stopwords_multiple_stopwords @p.opt "arg1", :default => false @p.opt "arg2", :default => false @p.stop_on %w(happy sad) opts = @p.parse %w(happy sad --arg1 --arg2) assert_equal false, opts["arg1"] assert_equal false, opts["arg2"] ## restart parsing @p.leftovers.shift opts = @p.parse @p.leftovers assert_equal false, opts["arg1"] assert_equal false, opts["arg2"] ## restart parsing again @p.leftovers.shift opts = @p.parse @p.leftovers assert_equal true, opts["arg1"] assert_equal true, opts["arg2"] end def test_stopwords_with_short_args @p.opt :global_option, "This is a global option", :short => "-g" @p.stop_on %w(sub-command-1 sub-command-2) global_opts = @p.parse %w(-g sub-command-1 -c) cmd = @p.leftovers.shift @q = Parser.new @q.opt :cmd_option, "This is an option only for the subcommand", :short => "-c" cmd_opts = @q.parse @p.leftovers assert_equal true, global_opts[:global_option] assert_nil global_opts[:cmd_option] assert_equal true, cmd_opts[:cmd_option] assert_nil cmd_opts[:global_option] assert_equal cmd, "sub-command-1" assert_equal @q.leftovers, [] end def assert_parses_correctly(parser, commandline, expected_opts, expected_leftovers) opts = parser.parse commandline assert_equal expected_opts, opts assert_equal expected_leftovers, parser.leftovers end def test_unknown_subcommand @p.opt :global_flag, "Global flag", :short => "-g", :type => :flag @p.opt :global_param, "Global parameter", :short => "-p", :default => 5 @p.stop_on_unknown expected_opts = { :global_flag => true, :help => false, :global_param => 5, :global_flag_given => true } expected_leftovers = [ "my_subcommand", "-c" ] assert_parses_correctly @p, %w(--global-flag my_subcommand -c), \ expected_opts, expected_leftovers assert_parses_correctly @p, %w(-g my_subcommand -c), \
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
true
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/trollop-2.1.2/lib/trollop.rb
_vendor/ruby/2.6.0/gems/trollop-2.1.2/lib/trollop.rb
# lib/trollop.rb -- trollop command-line processing library # Copyright (c) 2008-2014 William Morgan. # Copyright (c) 2014 Red Hat, Inc. # trollop is licensed under the same terms as Ruby. require 'date' module Trollop VERSION = "2.1.2" ## Thrown by Parser in the event of a commandline error. Not needed if ## you're using the Trollop::options entry. class CommandlineError < StandardError; end ## Thrown by Parser if the user passes in '-h' or '--help'. Handled ## automatically by Trollop#options. class HelpNeeded < StandardError; end ## Thrown by Parser if the user passes in '-v' or '--version'. Handled ## automatically by Trollop#options. class VersionNeeded < StandardError; end ## Regex for floating point numbers FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?[\d]+)?$/ ## Regex for parameters PARAM_RE = /^-(-|\.$|[^\d\.])/ ## The commandline parser. In typical usage, the methods in this class ## will be handled internally by Trollop::options. In this case, only the ## #opt, #banner and #version, #depends, and #conflicts methods will ## typically be called. ## ## If you want to instantiate this class yourself (for more complicated ## argument-parsing logic), call #parse to actually produce the output hash, ## and consider calling it from within ## Trollop::with_standard_exception_handling. class Parser ## The set of values that indicate a flag option when passed as the ## +:type+ parameter of #opt. FLAG_TYPES = [:flag, :bool, :boolean] ## The set of values that indicate a single-parameter (normal) option when ## passed as the +:type+ parameter of #opt. ## ## A value of +io+ corresponds to a readable IO resource, including ## a filename, URI, or the strings 'stdin' or '-'. SINGLE_ARG_TYPES = [:int, :integer, :string, :double, :float, :io, :date] ## The set of values that indicate a multiple-parameter option (i.e., that ## takes multiple space-separated values on the commandline) when passed as ## the +:type+ parameter of #opt. MULTI_ARG_TYPES = [:ints, :integers, :strings, :doubles, :floats, :ios, :dates] ## The complete set of legal values for the +:type+ parameter of #opt. TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES INVALID_SHORT_ARG_REGEX = /[\d-]/ #:nodoc: ## The values from the commandline that were not interpreted by #parse. attr_reader :leftovers ## The complete configuration hashes for each option. (Mainly useful ## for testing.) attr_reader :specs ## A flag that determines whether or not to raise an error if the parser is passed one or more ## options that were not registered ahead of time. If 'true', then the parser will simply ## ignore options that it does not recognize. attr_accessor :ignore_invalid_options ## Initializes the parser, and instance-evaluates any block given. def initialize *a, &b @version = nil @leftovers = [] @specs = {} @long = {} @short = {} @order = [] @constraints = [] @stop_words = [] @stop_on_unknown = false #instance_eval(&b) if b # can't take arguments cloaker(&b).bind(self).call(*a) if b end ## Define an option. +name+ is the option name, a unique identifier ## for the option that you will use internally, which should be a ## symbol or a string. +desc+ is a string description which will be ## displayed in help messages. ## ## Takes the following optional arguments: ## ## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s. ## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+. ## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given. ## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the the commandline the value will be +false+. ## [+:required+] If set to +true+, the argument must be provided on the commandline. ## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.) ## ## Note that there are two types of argument multiplicity: an argument ## can take multiple values, e.g. "--arg 1 2 3". An argument can also ## be allowed to occur multiple times, e.g. "--arg 1 --arg 2". ## ## Arguments that take multiple values should have a +:type+ parameter ## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+ ## value of an array of the correct type (e.g. [String]). The ## value of this argument will be an array of the parameters on the ## commandline. ## ## Arguments that can occur multiple times should be marked with ## +:multi+ => +true+. The value of this argument will also be an array. ## In contrast with regular non-multi options, if not specified on ## the commandline, the default value will be [], not nil. ## ## These two attributes can be combined (e.g. +:type+ => +:strings+, ## +:multi+ => +true+), in which case the value of the argument will be ## an array of arrays. ## ## There's one ambiguous case to be aware of: when +:multi+: is true and a ## +:default+ is set to an array (of something), it's ambiguous whether this ## is a multi-value argument as well as a multi-occurrence argument. ## In thise case, Trollop assumes that it's not a multi-value argument. ## If you want a multi-value, multi-occurrence argument with a default ## value, you must specify +:type+ as well. def opt name, desc="", opts={}, &b raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? name ## fill in :type opts[:type] = # normalize case opts[:type] when :boolean, :bool; :flag when :integer; :int when :integers; :ints when :double; :float when :doubles; :floats when Class case opts[:type].name when 'TrueClass', 'FalseClass'; :flag when 'String'; :string when 'Integer'; :int when 'Float'; :float when 'IO'; :io when 'Date'; :date else raise ArgumentError, "unsupported argument type '#{opts[:type].class.name}'" end when nil; nil else raise ArgumentError, "unsupported argument type '#{opts[:type]}'" unless TYPES.include?(opts[:type]) opts[:type] end ## for options with :multi => true, an array default doesn't imply ## a multi-valued argument. for that you have to specify a :type ## as well. (this is how we disambiguate an ambiguous situation; ## see the docs for Parser#opt for details.) disambiguated_default = if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type] opts[:default].first else opts[:default] end type_from_default = case disambiguated_default when Integer; :int when Numeric; :float when TrueClass, FalseClass; :flag when String; :string when IO; :io when Date; :date when Array if opts[:default].empty? if opts[:type] raise ArgumentError, "multiple argument type must be plural" unless MULTI_ARG_TYPES.include?(opts[:type]) nil else raise ArgumentError, "multiple argument type cannot be deduced from an empty array for '#{opts[:default][0].class.name}'" end else case opts[:default][0] # the first element determines the types when Integer; :ints when Numeric; :floats when String; :strings when IO; :ios when Date; :dates else raise ArgumentError, "unsupported multiple argument type '#{opts[:default][0].class.name}'" end end when nil; nil else raise ArgumentError, "unsupported argument type '#{opts[:default].class.name}'" end raise ArgumentError, ":type specification and default type don't match (default type is #{type_from_default})" if opts[:type] && type_from_default && opts[:type] != type_from_default opts[:type] = opts[:type] || type_from_default || :flag ## fill in :long opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.gsub("_", "-") opts[:long] = case opts[:long] when /^--([^-].*)$/; $1 when /^[^-]/; opts[:long] else; raise ArgumentError, "invalid long option name #{opts[:long].inspect}" end raise ArgumentError, "long option name #{opts[:long].inspect} is already taken; please specify a (different) :long" if @long[opts[:long]] ## fill in :short opts[:short] = opts[:short].to_s if opts[:short] && opts[:short] != :none opts[:short] = case opts[:short] when /^-(.)$/; $1 when nil, :none, /^.$/; opts[:short] else raise ArgumentError, "invalid short option name '#{opts[:short].inspect}'" end if opts[:short] raise ArgumentError, "short option name #{opts[:short].inspect} is already taken; please specify a (different) :short" if @short[opts[:short]] raise ArgumentError, "a short option name can't be a number or a dash" if opts[:short] =~ INVALID_SHORT_ARG_REGEX end ## fill in :default for flags opts[:default] = false if opts[:type] == :flag && opts[:default].nil? ## autobox :default for :multi (multi-occurrence) arguments opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array) ## fill in :multi opts[:multi] ||= false opts[:callback] ||= b if block_given? opts[:desc] ||= desc @long[opts[:long]] = name @short[opts[:short]] = name if opts[:short] && opts[:short] != :none @specs[name] = opts @order << [:opt, name] end ## Sets the version string. If set, the user can request the version ## on the commandline. Should probably be of the form "<program name> ## <version number>". def version(s = nil); @version = s if s; @version end ## Sets the usage string. If set the message will be printed as the ## first line in the help (educate) output and ending in two new ## lines. def usage(s = nil) ; @usage = s if s; @usage end ## Adds a synopsis (command summary description) right below the ## usage line, or as the first line if usage isn't specified. def synopsis(s = nil) ; @synopsis = s if s; @synopsis end ## Adds text to the help display. Can be interspersed with calls to ## #opt to build a multi-section help page. def banner s; @order << [:text, s] end alias :text :banner ## Marks two (or more!) options as requiring each other. Only handles ## undirected (i.e., mutual) dependencies. Directed dependencies are ## better modeled with Trollop::die. def depends *syms syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] } @constraints << [:depends, syms] end ## Marks two (or more!) options as conflicting. def conflicts *syms syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] } @constraints << [:conflicts, syms] end ## Defines a set of words which cause parsing to terminate when ## encountered, such that any options to the left of the word are ## parsed as usual, and options to the right of the word are left ## intact. ## ## A typical use case would be for subcommand support, where these ## would be set to the list of subcommands. A subsequent Trollop ## invocation would then be used to parse subcommand options, after ## shifting the subcommand off of ARGV. def stop_on *words @stop_words = [*words].flatten end ## Similar to #stop_on, but stops on any unknown word when encountered ## (unless it is a parameter for an argument). This is useful for ## cases where you don't know the set of subcommands ahead of time, ## i.e., without first parsing the global options. def stop_on_unknown @stop_on_unknown = true end ## Parses the commandline. Typically called by Trollop::options, ## but you can call it directly if you need more control. ## ## throws CommandlineError, HelpNeeded, and VersionNeeded exceptions. def parse cmdline=ARGV vals = {} required = {} opt :version, "Print version and exit" if @version && ! ( @specs[:version] || @long["version"]) opt :help, "Show this message" unless @specs[:help] || @long["help"] @specs.each do |sym, opts| required[sym] = true if opts[:required] vals[sym] = opts[:default] vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil end resolve_default_short_options! ## resolve symbols given_args = {} @leftovers = each_arg cmdline do |arg, params| ## handle --no- forms arg, negative_given = if arg =~ /^--no-([^-]\S*)$/ ["--#{$1}", true] else [arg, false] end sym = case arg when /^-([^-])$/; @short[$1] when /^--([^-]\S*)$/; @long[$1] || @long["no-#{$1}"] else; raise CommandlineError, "invalid argument syntax: '#{arg}'" end sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments next 0 if ignore_invalid_options && !sym raise CommandlineError, "unknown argument '#{arg}'" unless sym if given_args.include?(sym) && !@specs[sym][:multi] raise CommandlineError, "option '#{arg}' specified multiple times" end given_args[sym] ||= {} given_args[sym][:arg] = arg given_args[sym][:negative_given] = negative_given given_args[sym][:params] ||= [] # The block returns the number of parameters taken. num_params_taken = 0 unless params.nil? if SINGLE_ARG_TYPES.include?(@specs[sym][:type]) given_args[sym][:params] << params[0, 1] # take the first parameter num_params_taken = 1 elsif MULTI_ARG_TYPES.include?(@specs[sym][:type]) given_args[sym][:params] << params # take all the parameters num_params_taken = params.size end end num_params_taken end ## check for version and help args raise VersionNeeded if given_args.include? :version raise HelpNeeded if given_args.include? :help ## check constraint satisfaction @constraints.each do |type, syms| constraint_sym = syms.find { |sym| given_args[sym] } next unless constraint_sym case type when :depends syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym } when :conflicts syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) } end end required.each do |sym, val| raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym end ## parse parameters given_args.each do |sym, given_data| arg, params, negative_given = given_data.values_at :arg, :params, :negative_given opts = @specs[sym] if params.empty? && opts[:type] != :flag raise CommandlineError, "option '#{arg}' needs a parameter" unless opts[:default] params << (opts[:default].kind_of?(Array) ? opts[:default].clone : [opts[:default]]) end vals["#{sym}_given".intern] = true # mark argument as specified on the commandline case opts[:type] when :flag vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given) when :int, :ints vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } } when :float, :floats vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } } when :string, :strings vals[sym] = params.map { |pg| pg.map { |p| p.to_s } } when :io, :ios vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } } when :date, :dates vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } } end if SINGLE_ARG_TYPES.include?(opts[:type]) if opts[:multi] # multiple options, each with a single parameter vals[sym] = vals[sym].map { |p| p[0] } else # single parameter vals[sym] = vals[sym][0][0] end elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi] vals[sym] = vals[sym][0] # single option, with multiple parameters end # else: multiple options, with multiple parameters opts[:callback].call(vals[sym]) if opts.has_key?(:callback) end ## modify input in place with only those ## arguments we didn't process cmdline.clear @leftovers.each { |l| cmdline << l } ## allow openstruct-style accessors class << vals def method_missing(m, *args) self[m] || self[m.to_s] end end vals end def parse_date_parameter param, arg #:nodoc: begin begin require 'chronic' time = Chronic.parse(param) rescue LoadError # chronic is not available end time ? Date.new(time.year, time.month, time.day) : Date.parse(param) rescue ArgumentError raise CommandlineError, "option '#{arg}' needs a date" end end ## Print the help message to +stream+. def educate stream=$stdout width # hack: calculate it now; otherwise we have to be careful not to # call this unless the cursor's at the beginning of a line. left = {} @specs.each do |name, spec| left[name] = (spec[:short] && spec[:short] != :none ? "-#{spec[:short]}" : "") + (spec[:short] && spec[:short] != :none ? ", " : "") + "--#{spec[:long]}" + case spec[:type] when :flag; "" when :int; "=<i>" when :ints; "=<i+>" when :string; "=<s>" when :strings; "=<s+>" when :float; "=<f>" when :floats; "=<f+>" when :io; "=<filename/uri>" when :ios; "=<filename/uri+>" when :date; "=<date>" when :dates; "=<date+>" end + (spec[:type] == :flag && spec[:default] ? ", --no-#{spec[:long]}" : "") end leftcol_width = left.values.map { |s| s.length }.max || 0 rightcol_start = leftcol_width + 6 # spaces unless @order.size > 0 && @order.first.first == :text command_name = File.basename($0).gsub(/\.[^.]+$/, '') stream.puts "Usage: #{command_name} #@usage\n" if @usage stream.puts "#@synopsis\n" if @synopsis stream.puts if @usage or @synopsis stream.puts "#@version\n" if @version stream.puts "Options:" end @order.each do |what, opt| if what == :text stream.puts wrap(opt) next end spec = @specs[opt] stream.printf " %-#{leftcol_width}s ", left[opt] desc = spec[:desc] + begin default_s = case spec[:default] when $stdout; "<stdout>" when $stdin; "<stdin>" when $stderr; "<stderr>" when Array spec[:default].join(", ") else spec[:default].to_s end if spec[:default] if spec[:desc] =~ /\.$/ " (Default: #{default_s})" else " (default: #{default_s})" end else "" end end stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start) end end def width #:nodoc: @width ||= if $stdout.tty? begin require 'io/console' IO.console.winsize.last rescue LoadError, NoMethodError, Errno::ENOTTY, Errno::EBADF, Errno::EINVAL legacy_width end else 80 end end def legacy_width # Support for older Rubies where io/console is not available `tput cols`.to_i rescue Errno::ENOENT 80 end private :legacy_width def wrap str, opts={} # :nodoc: if str == "" [""] else inner = false str.split("\n").map do |s| line = wrap_line s, opts.merge(:inner => inner) inner = true line end.flatten end end ## The per-parser version of Trollop::die (see that for documentation). def die arg, msg if msg $stderr.puts "Error: argument --#{@specs[arg][:long]} #{msg}." else $stderr.puts "Error: #{arg}." end $stderr.puts "Try --help for help." exit(-1) end private ## yield successive arg, parameter pairs def each_arg args remains = [] i = 0 until i >= args.length if @stop_words.member? args[i] return remains += args[i .. -1] end case args[i] when /^--$/ # arg terminator return remains += args[(i + 1) .. -1] when /^--(\S+?)=(.*)$/ # long argument with equals yield "--#{$1}", [$2] i += 1 when /^--(\S+)$/ # long argument params = collect_argument_parameters(args, i + 1) if params.empty? yield args[i], nil i += 1 else num_params_taken = yield args[i], params unless num_params_taken if @stop_on_unknown return remains += args[i + 1 .. -1] else remains += params end end i += 1 + num_params_taken end when /^-(\S+)$/ # one or more short arguments shortargs = $1.split(//) shortargs.each_with_index do |a, j| if j == (shortargs.length - 1) params = collect_argument_parameters(args, i + 1) if params.empty? yield "-#{a}", nil i += 1 else num_params_taken = yield "-#{a}", params unless num_params_taken if @stop_on_unknown return remains += args[i + 1 .. -1] else remains += params end end i += 1 + num_params_taken end else yield "-#{a}", nil end end else if @stop_on_unknown return remains += args[i .. -1] else remains << args[i] i += 1 end end end remains end def parse_integer_parameter param, arg raise CommandlineError, "option '#{arg}' needs an integer" unless param =~ /^-?[\d_]+$/ param.to_i end def parse_float_parameter param, arg raise CommandlineError, "option '#{arg}' needs a floating-point number" unless param =~ FLOAT_RE param.to_f end def parse_io_parameter param, arg case param when /^(stdin|-)$/i; $stdin else require 'open-uri' begin open param rescue SystemCallError => e raise CommandlineError, "file or url for option '#{arg}' cannot be opened: #{e.message}" end end end def collect_argument_parameters args, start_at params = [] pos = start_at while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) do params << args[pos] pos += 1 end params end def resolve_default_short_options! @order.each do |type, name| opts = @specs[name] next if type != :opt || opts[:short] c = opts[:long].split(//).find { |d| d !~ INVALID_SHORT_ARG_REGEX && !@short.member?(d) } if c # found a character to use opts[:short] = c @short[c] = name end end end def wrap_line str, opts={} prefix = opts[:prefix] || 0 width = opts[:width] || (self.width - 1) start = 0 ret = [] until start > str.length nextt = if start + width >= str.length str.length else x = str.rindex(/\s/, start + width) x = str.index(/\s/, start) if x && x < start x || str.length end ret << ((ret.empty? && !opts[:inner]) ? "" : " " * prefix) + str[start ... nextt] start = nextt + 1 end ret end ## instance_eval but with ability to handle block arguments ## thanks to _why: http://redhanded.hobix.com/inspect/aBlockCostume.html def cloaker &b (class << self; self; end).class_eval do define_method :cloaker_, &b meth = instance_method :cloaker_ remove_method :cloaker_ meth end end end ## The easy, syntactic-sugary entry method into Trollop. Creates a Parser, ## passes the block to it, then parses +args+ with it, handling any errors or ## requests for help or version information appropriately (and then exiting). ## Modifies +args+ in place. Returns a hash of option values. ## ## The block passed in should contain zero or more calls to +opt+ ## (Parser#opt), zero or more calls to +text+ (Parser#text), and ## probably a call to +version+ (Parser#version). ## ## The returned block contains a value for every option specified with ## +opt+. The value will be the value given on the commandline, or the ## default value if the option was not specified on the commandline. For ## every option specified on the commandline, a key "<option ## name>_given" will also be set in the hash. ## ## Example: ## ## require 'trollop' ## opts = Trollop::options do ## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false ## opt :name, "Monkey name", :type => :string # a string --name <s>, defaulting to nil ## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4 ## end ## ## ## if called with no arguments ## p opts # => {:monkey=>false, :name=>nil, :num_limbs=>4, :help=>false} ## ## ## if called with --monkey ## p opts # => {:monkey=>true, :name=>nil, :num_limbs=>4, :help=>false, :monkey_given=>true} ## ## See more examples at http://trollop.rubyforge.org. def options args=ARGV, *a, &b @last_parser = Parser.new(*a, &b) with_standard_exception_handling(@last_parser) { @last_parser.parse args } end ## If Trollop::options doesn't do quite what you want, you can create a Parser ## object and call Parser#parse on it. That method will throw CommandlineError, ## HelpNeeded and VersionNeeded exceptions when necessary; if you want to ## have these handled for you in the standard manner (e.g. show the help ## and then exit upon an HelpNeeded exception), call your code from within ## a block passed to this method. ## ## Note that this method will call System#exit after handling an exception! ## ## Usage example: ## ## require 'trollop' ## p = Trollop::Parser.new do ## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false ## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true ## end ## ## opts = Trollop::with_standard_exception_handling p do ## o = p.parse ARGV ## raise Trollop::HelpNeeded if ARGV.empty? # show help screen ## o ## end ## ## Requires passing in the parser object. def with_standard_exception_handling parser begin yield rescue CommandlineError => e $stderr.puts "Error: #{e.message}." $stderr.puts "Try --help for help." exit(-1) rescue HelpNeeded parser.educate exit rescue VersionNeeded puts parser.version exit end end ## Informs the user that their usage of 'arg' was wrong, as detailed by ## 'msg', and dies. Example: ## ## options do ## opt :volume, :default => 0.0 ## end ## ## die :volume, "too loud" if opts[:volume] > 10.0 ## die :volume, "too soft" if opts[:volume] < 0.1 ## ## In the one-argument case, simply print that message, a notice ## about -h, and die. Example: ## ## options do ## opt :whatever # ... ## end ## ## Trollop::die "need at least one filename" if ARGV.empty? def die arg, msg=nil if @last_parser @last_parser.die arg, msg else raise ArgumentError, "Trollop::die can only be called after Trollop::options" end end ## Displays the help message and dies. Example: ## ## options do ## opt :volume, :default => 0.0 ## banner <<-EOS ## Usage: ## #$0 [options] <name> ## where [options] are: ## EOS ## end ## ## Trollop::educate if ARGV.empty? def educate if @last_parser @last_parser.educate exit else raise ArgumentError, "Trollop::educate can only be called after Trollop::options" end end module_function :options, :die, :educate, :with_standard_exception_handling end # module
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/test_helper.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/test_helper.rb
$KCODE = 'u' if RUBY_VERSION <= '1.9' require 'minitest/autorun' TEST_CASE = defined?(Minitest::Test) ? Minitest::Test : MiniTest::Unit::TestCase # TODO: Remove these aliases and update tests accordingly. class TEST_CASE alias :assert_raise :assert_raises alias :assert_not_equal :refute_equal def assert_nothing_raised(*args) yield end end require 'bundler/setup' require 'i18n' require 'mocha/setup' require 'test_declarative' class I18n::TestCase < TEST_CASE def self.key_value? defined?(ActiveSupport) end def setup super I18n.enforce_available_locales = false end def teardown I18n.locale = nil I18n.default_locale = nil I18n.load_path = nil I18n.available_locales = nil I18n.backend = nil I18n.default_separator = nil I18n.enforce_available_locales = true super end protected def translations I18n.backend.instance_variable_get(:@translations) end def store_translations(locale, data) I18n.backend.store_translations(locale, data) end def locales_dir File.dirname(__FILE__) + '/test_data/locales' end end class DummyRackApp def call(env) I18n.locale = :es end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n_test.rb
# encoding: utf-8 require 'test_helper' class I18nTest < I18n::TestCase def setup super store_translations(:en, :currency => { :format => { :separator => '.', :delimiter => ',', } }) store_translations(:nl, :currency => { :format => { :separator => ',', :delimiter => '.', } }) store_translations(:en, "true" => "Yes", "false" => "No") end test "exposes its VERSION constant" do assert I18n::VERSION end test "uses the simple backend by default" do assert I18n.backend.is_a?(I18n::Backend::Simple) end test "can set the backend" do begin assert_nothing_raised { I18n.backend = self } assert_equal self, I18n.backend ensure I18n.backend = I18n::Backend::Simple.new end end test "uses :en as a default_locale by default" do assert_equal :en, I18n.default_locale end test "can set the default locale" do begin assert_nothing_raised { I18n.default_locale = 'de' } assert_equal :de, I18n.default_locale ensure I18n.default_locale = :en end end test "default_locale= doesn't ignore junk" do assert_raise(NoMethodError) { I18n.default_locale = Class } end test "raises an I18n::InvalidLocale exception when setting an unavailable default locale" do begin I18n.config.enforce_available_locales = true assert_raise(I18n::InvalidLocale) { I18n.default_locale = :klingon } ensure I18n.config.enforce_available_locales = false end end test "uses the default locale as a locale by default" do assert_equal I18n.default_locale, I18n.locale end test "sets the current locale to Thread.current" do assert_nothing_raised { I18n.locale = 'de' } assert_equal :de, I18n.locale assert_equal :de, Thread.current[:i18n_config].locale I18n.locale = :en end test "locale= doesn't ignore junk" do assert_raise(NoMethodError) { I18n.locale = Class } end test "raises an I18n::InvalidLocale exception when setting an unavailable locale" do begin I18n.config.enforce_available_locales = true assert_raise(I18n::InvalidLocale) { I18n.locale = :klingon } ensure I18n.config.enforce_available_locales = false end end test "can set the configuration object" do begin I18n.config = self assert_equal self, I18n.config assert_equal self, Thread.current[:i18n_config] ensure I18n.config = ::I18n::Config.new end end test "locale is not shared between configurations" do a = I18n::Config.new b = I18n::Config.new a.locale = :fr b.locale = :es assert_equal :fr, a.locale assert_equal :es, b.locale assert_equal :en, I18n.locale end test "other options are shared between configurations" do begin a = I18n::Config.new b = I18n::Config.new a.default_locale = :fr b.default_locale = :es assert_equal :es, a.default_locale assert_equal :es, b.default_locale assert_equal :es, I18n.default_locale ensure I18n.default_locale = :en end end test "uses a dot as a default_separator by default" do assert_equal '.', I18n.default_separator end test "can set the default_separator" do begin assert_nothing_raised { I18n.default_separator = "\001" } ensure I18n.default_separator = '.' end end test "normalize_keys normalizes given locale, keys and scope to an array of single-key symbols" do assert_equal [:en, :foo, :bar], I18n.normalize_keys(:en, :bar, :foo) assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, :'baz.buz', :'foo.bar') assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, 'baz.buz', 'foo.bar') assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, %w(baz buz), %w(foo bar)) assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, [:baz, :buz], [:foo, :bar]) end test "normalize_keys discards empty keys" do assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, :'baz..buz', :'foo..bar') assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, :'baz......buz', :'foo......bar') assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, ['baz', nil, '', 'buz'], ['foo', nil, '', 'bar']) end test "normalize_keys uses a given separator" do assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, :'baz|buz', :'foo|bar', '|') end test "can set the exception_handler" do begin previous_exception_handler = I18n.exception_handler assert_nothing_raised { I18n.exception_handler = :custom_exception_handler } ensure I18n.exception_handler = previous_exception_handler end end test "uses a custom exception handler set to I18n.exception_handler" do begin previous_exception_handler = I18n.exception_handler I18n.exception_handler = :custom_exception_handler I18n.expects(:custom_exception_handler) I18n.translate :bogus ensure I18n.exception_handler = previous_exception_handler end end test "uses a custom exception handler passed as an option" do I18n.expects(:custom_exception_handler) I18n.translate(:bogus, :exception_handler => :custom_exception_handler) end test "delegates translate calls to the backend" do I18n.backend.expects(:translate).with('de', :foo, {}) I18n.translate :foo, :locale => 'de' end test "delegates localize calls to the backend" do I18n.backend.expects(:localize).with('de', :whatever, :default, {}) I18n.localize :whatever, :locale => 'de' end test "translate given no locale uses the current locale" do I18n.backend.expects(:translate).with(:en, :foo, {}) I18n.translate :foo end test "translate works with nested symbol keys" do assert_equal ".", I18n.t(:'currency.format.separator') end test "translate works with nested string keys" do assert_equal ".", I18n.t('currency.format.separator') end test "translate with an array as a scope works" do assert_equal ".", I18n.t(:separator, :scope => %w(currency format)) end test "translate with an array containing dot separated strings as a scope works" do assert_equal ".", I18n.t(:separator, :scope => ['currency.format']) end test "translate with an array of keys and a dot separated string as a scope works" do assert_equal [".", ","], I18n.t(%w(separator delimiter), :scope => 'currency.format') end test "translate with an array of dot separated keys and a scope works" do assert_equal [".", ","], I18n.t(%w(format.separator format.delimiter), :scope => 'currency') end # def test_translate_given_no_args_raises_missing_translation_data # assert_equal "translation missing: en, no key", I18n.t # end test "translate given a bogus key returns an error message" do assert_equal "translation missing: en.bogus", I18n.t(:bogus) end test "translate given an empty string as a key raises an I18n::ArgumentError" do assert_raise(I18n::ArgumentError) { I18n.t("") } end test "translate given an empty symbol as a key raises an I18n::ArgumentError" do assert_raise(I18n::ArgumentError) { I18n.t(:"") } end test "translate given an array with empty string as a key raises an I18n::ArgumentError" do assert_raise(I18n::ArgumentError) { I18n.t(["", :foo]) } end test "translate given an empty array as a key returns empty array" do assert_equal [], I18n.t([]) end test "translate given nil returns nil" do assert_nil I18n.t(nil) end test "translate given an unavailable locale rases an I18n::InvalidLocale" do begin I18n.config.enforce_available_locales = true assert_raise(I18n::InvalidLocale) { I18n.t(:foo, :locale => 'klingon') } ensure I18n.config.enforce_available_locales = false end end test "translate given true as a key works" do assert_equal "Yes", I18n.t(true) end test "translate given false as a key works" do assert_equal "No", I18n.t(false) end test "available_locales can be replaced at runtime" do begin I18n.config.enforce_available_locales = true assert_raise(I18n::InvalidLocale) { I18n.t(:foo, :locale => 'klingon') } old_locales, I18n.config.available_locales = I18n.config.available_locales, [:klingon] I18n.t(:foo, :locale => 'klingon') ensure I18n.config.enforce_available_locales = false I18n.config.available_locales = old_locales end end test "available_locales_set should return a set" do assert_equal Set, I18n.config.available_locales_set.class assert_equal I18n.config.available_locales.size * 2, I18n.config.available_locales_set.size end test "exists? given an existing key will return true" do assert_equal true, I18n.exists?(:currency) end test "exists? given a non-existing key will return false" do assert_equal false, I18n.exists?(:bogus) end test "exists? given an existing dot-separated key will return true" do assert_equal true, I18n.exists?('currency.format.delimiter') end test "exists? given a non-existing dot-separated key will return false" do assert_equal false, I18n.exists?('currency.format.bogus') end test "exists? given an existing key and an existing locale will return true" do assert_equal true, I18n.exists?(:currency, :nl) end test "exists? given a non-existing key and an existing locale will return false" do assert_equal false, I18n.exists?(:bogus, :nl) end test "localize given nil raises an I18n::ArgumentError" do assert_raise(I18n::ArgumentError) { I18n.l nil } end test "localize given nil and default returns default" do assert_nil I18n.l(nil, :default => nil) end test "localize given an Object raises an I18n::ArgumentError" do assert_raise(I18n::ArgumentError) { I18n.l Object.new } end test "localize given an unavailable locale rases an I18n::InvalidLocale" do begin I18n.config.enforce_available_locales = true assert_raise(I18n::InvalidLocale) { I18n.l(Time.now, :locale => 'klingon') } ensure I18n.config.enforce_available_locales = false end end test "can use a lambda as an exception handler" do begin previous_exception_handler = I18n.exception_handler I18n.exception_handler = Proc.new { |exception, locale, key, options| key } assert_equal :test_proc_handler, I18n.translate(:test_proc_handler) ensure I18n.exception_handler = previous_exception_handler end end test "can use an object responding to #call as an exception handler" do begin previous_exception_handler = I18n.exception_handler I18n.exception_handler = Class.new do def call(exception, locale, key, options); key; end end.new assert_equal :test_proc_handler, I18n.translate(:test_proc_handler) ensure I18n.exception_handler = previous_exception_handler end end test "I18n.with_locale temporarily sets the given locale" do store_translations(:en, :foo => 'Foo in :en') store_translations(:de, :foo => 'Foo in :de') store_translations(:pl, :foo => 'Foo in :pl') I18n.with_locale { assert_equal [:en, 'Foo in :en'], [I18n.locale, I18n.t(:foo)] } I18n.with_locale(:de) { assert_equal [:de, 'Foo in :de'], [I18n.locale, I18n.t(:foo)] } I18n.with_locale(:pl) { assert_equal [:pl, 'Foo in :pl'], [I18n.locale, I18n.t(:foo)] } I18n.with_locale(:en) { assert_equal [:en, 'Foo in :en'], [I18n.locale, I18n.t(:foo)] } assert_equal I18n.default_locale, I18n.locale end test "I18n.with_locale resets the locale in case of errors" do assert_raise(I18n::ArgumentError) { I18n.with_locale(:pl) { raise I18n::ArgumentError } } assert_equal I18n.default_locale, I18n.locale end test "I18n.translitarate handles I18n::ArgumentError exception" do I18n::Backend::Transliterator.stubs(:get).raises(I18n::ArgumentError) I18n.exception_handler.expects(:call).raises(I18n::ArgumentError) assert_raise(I18n::ArgumentError) { I18n.transliterate("ąćó") } end test "I18n.translitarate raises I18n::ArgumentError exception" do I18n::Backend::Transliterator.stubs(:get).raises(I18n::ArgumentError) I18n.exception_handler.expects(:call).never assert_raise(I18n::ArgumentError) { I18n.transliterate("ąćó", :raise => true) } end test "transliterate given an unavailable locale rases an I18n::InvalidLocale" do begin I18n.config.enforce_available_locales = true assert_raise(I18n::InvalidLocale) { I18n.transliterate('string', :locale => 'klingon') } ensure I18n.config.enforce_available_locales = false end end test "transliterate non-ASCII chars not in map with default replacement char" do assert_equal "???", I18n.transliterate("日本語") end test "I18n.locale_available? returns true when the passed locale is available" do I18n.available_locales = [:en, :de] assert_equal true, I18n.locale_available?(:de) end test "I18n.locale_available? returns true when the passed locale is a string and is available" do I18n.available_locales = [:en, :de] assert_equal true, I18n.locale_available?('de') end test "I18n.locale_available? returns false when the passed locale is unavailable" do assert_equal false, I18n.locale_available?(:klingon) end test "I18n.enforce_available_locales! raises an I18n::InvalidLocale when the passed locale is unavailable" do begin I18n.config.enforce_available_locales = true assert_raise(I18n::InvalidLocale) { I18n.enforce_available_locales!(:klingon) } ensure I18n.config.enforce_available_locales = false end end test "I18n.enforce_available_locales! does nothing when the passed locale is available" do I18n.available_locales = [:en, :de] begin I18n.config.enforce_available_locales = true assert_nothing_raised { I18n.enforce_available_locales!(:en) } ensure I18n.config.enforce_available_locales = false end end test "I18n.enforce_available_locales config can be set to false" do begin I18n.config.enforce_available_locales = false assert_equal false, I18n.config.enforce_available_locales ensure I18n.config.enforce_available_locales = false end end test 'I18n.reload! reloads the set of locales that are enforced' do begin # Clear the backend that affects the available locales and somehow can remain # set from the last running test. # For instance, it contains enough translations to cause a false positive with # this test when ran with --seed=50992 I18n.backend = I18n::Backend::Simple.new assert !I18n.available_locales.include?(:de), "Available locales should not include :de at this point" I18n.enforce_available_locales = true assert_raise(I18n::InvalidLocale) { I18n.default_locale = :de } assert_raise(I18n::InvalidLocale) { I18n.locale = :de } store_translations(:de, :foo => 'Foo in :de') assert_raise(I18n::InvalidLocale) { I18n.default_locale = :de } assert_raise(I18n::InvalidLocale) { I18n.locale = :de } I18n.reload! store_translations(:en, :foo => 'Foo in :en') store_translations(:de, :foo => 'Foo in :de') store_translations(:pl, :foo => 'Foo in :pl') assert I18n.available_locales.include?(:de), ":de should now be allowed" assert I18n.available_locales.include?(:en), ":en should now be allowed" assert I18n.available_locales.include?(:pl), ":pl should now be allowed" assert_nothing_raised { I18n.default_locale = I18n.locale = :en } assert_nothing_raised { I18n.default_locale = I18n.locale = :de } assert_nothing_raised { I18n.default_locale = I18n.locale = :pl } ensure I18n.enforce_available_locales = false end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/run_all.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/run_all.rb
def bundle_check `bundle check` == "Resolving dependencies...\nThe Gemfile's dependencies are satisfied\n" end def execute(command) puts command system command end gemfiles = %w(Gemfile) + Dir['gemfiles/Gemfile*'].reject { |f| f.end_with?('.lock') } results = gemfiles.map do |gemfile| puts "\nBUNDLE_GEMFILE=#{gemfile}" ENV['BUNDLE_GEMFILE'] = File.expand_path("../../#{gemfile}", __FILE__) execute 'bundle install' unless bundle_check execute 'bundle exec rake test' end exit results.all?
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/core_ext/hash_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/core_ext/hash_test.rb
require 'test_helper' require 'i18n/core_ext/hash' class I18nCoreExtHashInterpolationTest < I18n::TestCase test "#deep_symbolize_keys" do hash = { 'foo' => { 'bar' => { 'baz' => 'bar' } } } expected = { :foo => { :bar => { :baz => 'bar' } } } assert_equal expected, hash.deep_symbolize_keys end test "#slice" do hash = { :foo => 'bar', :baz => 'bar' } expected = { :foo => 'bar' } assert_equal expected, hash.slice(:foo) end test "#slice non-existent key" do hash = { :foo => 'bar', :baz => 'bar' } expected = { :foo => 'bar' } assert_equal expected, hash.slice(:foo, :not_here) end test "#except" do hash = { :foo => 'bar', :baz => 'bar' } expected = { :foo => 'bar' } assert_equal expected, hash.except(:baz) end test "#deep_merge!" do hash = { :foo => { :bar => { :baz => 'bar' } }, :baz => 'bar' } hash.deep_merge!(:foo => { :bar => { :baz => 'foo' } }) expected = { :foo => { :bar => { :baz => 'foo' } }, :baz => 'bar' } assert_equal expected, hash end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/load_path_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/load_path_test.rb
require 'test_helper' class I18nLoadPathTest < I18n::TestCase def setup super I18n.locale = :en I18n.backend = I18n::Backend::Simple.new store_translations(:en, :foo => {:bar => 'bar', :baz => 'baz'}) end test "nested load paths do not break locale loading" do I18n.load_path = [[locales_dir + '/en.yml']] assert_equal "baz", I18n.t(:'foo.bar') end test "loading an empty yml file raises an InvalidLocaleData exception" do assert_raise I18n::InvalidLocaleData do I18n.load_path = [[locales_dir + '/invalid/empty.yml']] I18n.t(:'foo.bar', :default => "baz") end end test "loading an invalid yml file raises an InvalidLocaleData exception" do assert_raise I18n::InvalidLocaleData do I18n.load_path = [[locales_dir + '/invalid/syntax.yml']] I18n.t(:'foo.bar', :default => "baz") end end test "adding arrays of filenames to the load path does not break locale loading" do I18n.load_path << Dir[locales_dir + '/*.{rb,yml}'] assert_equal "baz", I18n.t(:'foo.bar') end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/middleware_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/middleware_test.rb
require 'test_helper' class I18nMiddlewareTest < I18n::TestCase def setup super I18n.default_locale = :fr @app = DummyRackApp.new @middleware = I18n::Middleware.new(@app) end test "middleware initializes new config object after request" do old_i18n_config_object_id = Thread.current[:i18n_config].object_id @middleware.call({}) updated_i18n_config_object_id = Thread.current[:i18n_config].object_id assert_not_equal updated_i18n_config_object_id, old_i18n_config_object_id end test "succesfully resets i18n locale to default locale by defining new config" do @middleware.call({}) assert_equal :fr, I18n.locale end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/gettext_plural_keys_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/gettext_plural_keys_test.rb
require 'test_helper' class I18nGettextPluralKeysTest < I18n::TestCase def setup super I18n::Gettext.plural_keys[:zz] = [:value1, :value2] end test "Returns the plural keys of the given locale if present" do assert_equal I18n::Gettext.plural_keys(:zz), [:value1, :value2] end test "Returns the plural keys of :en if given locale not present" do assert_equal I18n::Gettext.plural_keys(:yy), [:one, :other] end test "Returns the whole hash with no arguments" do assert_equal I18n::Gettext.plural_keys, { :en => [:one, :other], :zz => [:value1, :value2] } end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/interpolate_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/interpolate_test.rb
require 'test_helper' # thanks to Masao's String extensions, some tests taken from Masao's tests # http://github.com/mutoh/gettext/blob/edbbe1fa8238fa12c7f26f2418403015f0270e47/test/test_string.rb class I18nInterpolateTest < I18n::TestCase test "String interpolates a hash argument w/ named placeholders" do assert_equal "Masao Mutoh", I18n.interpolate("%{first} %{last}", :first => 'Masao', :last => 'Mutoh' ) end test "String interpolates a hash argument w/ named placeholders (reverse order)" do assert_equal "Mutoh, Masao", I18n.interpolate("%{last}, %{first}", :first => 'Masao', :last => 'Mutoh' ) end test "String interpolates named placeholders with sprintf syntax" do assert_equal "10, 43.4", I18n.interpolate("%<integer>d, %<float>.1f", :integer => 10, :float => 43.4) end test "String interpolates named placeholders with sprintf syntax, does not recurse" do assert_equal "%<not_translated>s", I18n.interpolate("%{msg}", :msg => '%<not_translated>s', :not_translated => 'should not happen' ) end test "String interpolation does not replace anything when no placeholders are given" do assert_equal "aaa", I18n.interpolate("aaa", :num => 1) end test "String interpolation sprintf behaviour equals Ruby 1.9 behaviour" do assert_equal "1", I18n.interpolate("%<num>d", :num => 1) assert_equal "0b1", I18n.interpolate("%<num>#b", :num => 1) assert_equal "foo", I18n.interpolate("%<msg>s", :msg => "foo") assert_equal "1.000000", I18n.interpolate("%<num>f", :num => 1.0) assert_equal " 1", I18n.interpolate("%<num>3.0f", :num => 1.0) assert_equal "100.00", I18n.interpolate("%<num>2.2f", :num => 100.0) assert_equal "0x64", I18n.interpolate("%<num>#x", :num => 100.0) assert_raise(ArgumentError) { I18n.interpolate("%<num>,d", :num => 100) } assert_raise(ArgumentError) { I18n.interpolate("%<num>/d", :num => 100) } end test "String interpolation raises an I18n::MissingInterpolationArgument when the string has extra placeholders" do assert_raise(I18n::MissingInterpolationArgument) do # Ruby 1.9 msg: "key not found" I18n.interpolate("%{first} %{last}", :first => 'Masao') end end test "String interpolation does not raise when extra values were passed" do assert_nothing_raised do assert_equal "Masao Mutoh", I18n.interpolate("%{first} %{last}", :first => 'Masao', :last => 'Mutoh', :salutation => 'Mr.' ) end end test "% acts as escape character in String interpolation" do assert_equal "%{first}", I18n.interpolate("%%{first}", :first => 'Masao') assert_equal "% 1", I18n.interpolate("%% %<num>d", :num => 1.0) assert_equal "%{num} %<num>d", I18n.interpolate("%%{num} %%<num>d", :num => 1) end def test_sprintf_mix_unformatted_and_formatted_named_placeholders assert_equal "foo 1.000000", I18n.interpolate("%{name} %<num>f", :name => "foo", :num => 1.0) end class RailsSafeBuffer < String def gsub(*args, &block) to_str.gsub(*args, &block) end end test "with String subclass that redefined gsub method" do assert_equal "Hello mars world", I18n.interpolate(RailsSafeBuffer.new("Hello %{planet} world"), :planet => 'mars') end end class I18nMissingInterpolationCustomHandlerTest < I18n::TestCase def setup super @old_handler = I18n.config.missing_interpolation_argument_handler I18n.config.missing_interpolation_argument_handler = lambda do |key, values, string| "missing key is #{key}, values are #{values.inspect}, given string is '#{string}'" end end def teardown I18n.config.missing_interpolation_argument_handler = @old_handler super end test "String interpolation can use custom missing interpolation handler" do assert_equal %|Masao missing key is last, values are {:first=>"Masao"}, given string is '%{first} %{last}'|, I18n.interpolate("%{first} %{last}", :first => 'Masao') end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/exceptions_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/i18n/exceptions_test.rb
require 'test_helper' class I18nExceptionsTest < I18n::TestCase def test_invalid_locale_stores_locale force_invalid_locale rescue I18n::ArgumentError => exception assert_nil exception.locale end test "passing an invalid locale raises an InvalidLocale exception" do force_invalid_locale do |exception| assert_equal 'nil is not a valid locale', exception.message end end test "MissingTranslation can be initialized without options" do exception = I18n::MissingTranslation.new(:en, 'foo') assert_equal({}, exception.options) end test "MissingTranslationData exception stores locale, key and options" do force_missing_translation_data do |exception| assert_equal 'de', exception.locale assert_equal :foo, exception.key assert_equal({:scope => :bar}, exception.options) end end test "MissingTranslationData message contains the locale and scoped key" do force_missing_translation_data do |exception| assert_equal 'translation missing: de.bar.foo', exception.message end end test "InvalidPluralizationData stores entry, count and key" do force_invalid_pluralization_data do |exception| assert_equal({:other => "bar"}, exception.entry) assert_equal 1, exception.count assert_equal :one, exception.key end end test "InvalidPluralizationData message contains count, data and missing key" do force_invalid_pluralization_data do |exception| assert_match '1', exception.message assert_match '{:other=>"bar"}', exception.message assert_match 'one', exception.message end end test "MissingInterpolationArgument stores key and string" do assert_raise(I18n::MissingInterpolationArgument) { force_missing_interpolation_argument } force_missing_interpolation_argument do |exception| assert_equal :bar, exception.key assert_equal "%{bar}", exception.string end end test "MissingInterpolationArgument message contains the missing and given arguments" do force_missing_interpolation_argument do |exception| assert_equal 'missing interpolation argument :bar in "%{bar}" ({:baz=>"baz"} given)', exception.message end end test "ReservedInterpolationKey stores key and string" do force_reserved_interpolation_key do |exception| assert_equal :scope, exception.key assert_equal "%{scope}", exception.string end end test "ReservedInterpolationKey message contains the reserved key" do force_reserved_interpolation_key do |exception| assert_equal 'reserved key :scope used in "%{scope}"', exception.message end end test "MissingTranslationData#new can be initialized with just two arguments" do assert I18n::MissingTranslationData.new('en', 'key') end private def force_invalid_locale I18n.translate(:foo, :locale => nil) rescue I18n::ArgumentError => e block_given? ? yield(e) : raise(e) end def force_missing_translation_data(options = {}) store_translations('de', :bar => nil) I18n.translate(:foo, options.merge(:scope => :bar, :locale => :de)) rescue I18n::ArgumentError => e block_given? ? yield(e) : raise(e) end def force_invalid_pluralization_data store_translations('de', :foo => { :other => 'bar' }) I18n.translate(:foo, :count => 1, :locale => :de) rescue I18n::ArgumentError => e block_given? ? yield(e) : raise(e) end def force_missing_interpolation_argument store_translations('de', :foo => "%{bar}") I18n.translate(:foo, :baz => 'baz', :locale => :de) rescue I18n::ArgumentError => e block_given? ? yield(e) : raise(e) end def force_reserved_interpolation_key store_translations('de', :foo => "%{scope}") I18n.translate(:foo, :baz => 'baz', :locale => :de) rescue I18n::ArgumentError => e block_given? ? yield(e) : raise(e) end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/fallbacks_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/fallbacks_test.rb
require 'test_helper' class I18nFallbacksApiTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Fallbacks end def setup I18n.backend = Backend.new super end include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization include I18n::Tests::Procs include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time include I18n::Tests::Localization::Procs test "make sure we use a backend with Fallbacks included" do assert_equal Backend, I18n.backend.class end # links: test that keys stored on one backend can link to keys stored on another backend end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/memoize_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/memoize_test.rb
require 'test_helper' class I18nMemoizeBackendWithSimpleApiTest < I18n::TestCase include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization include I18n::Tests::Procs include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time include I18n::Tests::Localization::Procs class MemoizeBackend < I18n::Backend::Simple include I18n::Backend::Memoize end def setup I18n.backend = MemoizeBackend.new super end test "make sure we use the MemoizeBackend backend" do assert_equal MemoizeBackend, I18n.backend.class end end class I18nMemoizeBackendWithKeyValueApiTest < I18n::TestCase include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time # include I18n::Tests::Procs # include I18n::Tests::Localization::Procs class MemoizeBackend < I18n::Backend::KeyValue include I18n::Backend::Memoize end def setup I18n.backend = MemoizeBackend.new({}) super end test "make sure we use the MemoizeBackend backend" do assert_equal MemoizeBackend, I18n.backend.class end end if I18n::TestCase.key_value?
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/override_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/override_test.rb
require 'test_helper' class I18nOverrideTest < I18n::TestCase module OverrideInverse def translate(*args) super(*args).reverse end alias :t :translate end module OverrideSignature def translate(*args) args.first + args[1] end alias :t :translate end def setup super @I18n = I18n.dup @I18n.backend = I18n::Backend::Simple.new end test "make sure modules can overwrite I18n methods" do @I18n.extend OverrideInverse @I18n.backend.store_translations('en', :foo => 'bar') assert_equal 'rab', @I18n.translate(:foo, :locale => 'en') assert_equal 'rab', @I18n.t(:foo, :locale => 'en') assert_equal 'rab', @I18n.translate!(:foo, :locale => 'en') assert_equal 'rab', @I18n.t!(:foo, :locale => 'en') end test "make sure modules can overwrite I18n signature" do exception = catch(:exception) do @I18n.t('Hello', 'Welcome message on home page', :tokenize => true, :throw => true) end assert exception.message @I18n.extend OverrideSignature assert_equal 'HelloWelcome message on home page', @I18n.translate('Hello', 'Welcome message on home page', :tokenize => true) # tr8n example end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/key_value_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/key_value_test.rb
require 'test_helper' class I18nKeyValueApiTest < I18n::TestCase include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization # include Tests::Api::Procs include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time # include Tests::Api::Localization::Procs def setup I18n.backend = I18n::Backend::KeyValue.new({}) super end test "make sure we use the KeyValue backend" do assert_equal I18n::Backend::KeyValue, I18n.backend.class end end if I18n::TestCase.key_value?
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/pluralization_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/pluralization_test.rb
require 'test_helper' class I18nPluralizationApiTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Pluralization end def setup I18n.backend = Backend.new super end include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization include I18n::Tests::Procs include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time include I18n::Tests::Localization::Procs test "make sure we use a backend with Pluralization included" do assert_equal Backend, I18n.backend.class end # links: test that keys stored on one backend can link to keys stored on another backend end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/simple_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/simple_test.rb
require 'test_helper' class I18nSimpleBackendApiTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Pluralization end def setup I18n.backend = I18n::Backend::Simple.new super end include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization include I18n::Tests::Procs include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time include I18n::Tests::Localization::Procs test "make sure we use the Simple backend" do assert_equal I18n::Backend::Simple, I18n.backend.class end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/chain_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/chain_test.rb
require 'test_helper' class I18nApiChainTest < I18n::TestCase def setup super I18n.backend = I18n::Backend::Chain.new(I18n::Backend::Simple.new, I18n.backend) end include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization include I18n::Tests::Procs include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time include I18n::Tests::Localization::Procs test "make sure we use the Chain backend" do assert_equal I18n::Backend::Chain, I18n.backend.class end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/all_features_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/all_features_test.rb
require 'test_helper' begin require 'rubygems' require 'active_support' rescue LoadError puts "not testing with Cache enabled because active_support can not be found" end class I18nAllFeaturesApiTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Metadata include I18n::Backend::Cache include I18n::Backend::Cascade include I18n::Backend::Fallbacks include I18n::Backend::Pluralization include I18n::Backend::Memoize end def setup I18n.backend = I18n::Backend::Chain.new(Backend.new, I18n::Backend::Simple.new) I18n.cache_store = cache_store super end def teardown I18n.cache_store.clear if I18n.cache_store I18n.cache_store = nil super end def cache_store ActiveSupport::Cache.lookup_store(:memory_store) if cache_available? end def cache_available? defined?(ActiveSupport) && defined?(ActiveSupport::Cache) end include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization include I18n::Tests::Procs include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time include I18n::Tests::Localization::Procs test "make sure we use a Chain backend with an all features backend" do assert_equal I18n::Backend::Chain, I18n.backend.class assert_equal Backend, I18n.backend.backends.first.class end # links: test that keys stored on one backend can link to keys stored on another backend end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/cascade_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/api/cascade_test.rb
require 'test_helper' class I18nCascadeApiTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Cascade end def setup I18n.backend = Backend.new super end include I18n::Tests::Basics include I18n::Tests::Defaults include I18n::Tests::Interpolation include I18n::Tests::Link include I18n::Tests::Lookup include I18n::Tests::Pluralization include I18n::Tests::Procs include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Time include I18n::Tests::Localization::Procs test "make sure we use a backend with Cascade included" do assert_equal Backend, I18n.backend.class end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/transliterator_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/transliterator_test.rb
# encoding: utf-8 require 'test_helper' class I18nBackendTransliterator < I18n::TestCase def setup super I18n.backend = I18n::Backend::Simple.new @proc = lambda { |n| n.upcase } @hash = { "ü" => "ue", "ö" => "oe", "a" => "a" } @transliterator = I18n::Backend::Transliterator.get end test "transliteration rule can be a proc" do store_translations(:xx, :i18n => {:transliterate => {:rule => @proc}}) assert_equal "HELLO", I18n.backend.transliterate(:xx, "hello") end test "transliteration rule can be a hash" do store_translations(:xx, :i18n => {:transliterate => {:rule => @hash}}) assert_equal "ue", I18n.backend.transliterate(:xx, "ü") end test "transliteration rule must be a proc or hash" do store_translations(:xx, :i18n => {:transliterate => {:rule => ""}}) assert_raise I18n::ArgumentError do I18n.backend.transliterate(:xx, "ü") end end test "transliterator defaults to latin => ascii when no rule is given" do assert_equal "AEroskobing", I18n.backend.transliterate(:xx, "Ærøskøbing") end test "default transliterator should not modify ascii characters" do (0..127).each do |byte| char = [byte].pack("U") assert_equal char, @transliterator.transliterate(char) end end test "default transliterator correctly transliterates latin characters" do # create string with range of Unicode's western characters with # diacritics, excluding the division and multiplication signs which for # some reason or other are floating in the middle of all the letters. string = (0xC0..0x17E).to_a.reject {|c| [0xD7, 0xF7].include? c}.pack("U*") string.split(//) do |char| assert_match %r{^[a-zA-Z']*$}, @transliterator.transliterate(string) end end test "should replace non-ASCII chars not in map with a replacement char" do assert_equal "abc?", @transliterator.transliterate("abcſ") end test "can replace non-ASCII chars not in map with a custom replacement string" do assert_equal "abc#", @transliterator.transliterate("abcſ", "#") end test "default transliterator raises errors for invalid UTF-8" do assert_raise ArgumentError do @transliterator.transliterate("a\x92b") end end test "I18n.transliterate should transliterate using a default transliterator" do assert_equal "aeo", I18n.transliterate("áèö") end test "I18n.transliterate should transliterate using a locale" do store_translations(:xx, :i18n => {:transliterate => {:rule => @hash}}) assert_equal "ue", I18n.transliterate("ü", :locale => :xx) end test "default transliterator fails with custom rules with uncomposed input" do char = [117, 776].pack("U*") # "ü" as ASCII "u" plus COMBINING DIAERESIS transliterator = I18n::Backend::Transliterator.get(@hash) assert_not_equal "ue", transliterator.transliterate(char) end test "DEFAULT_APPROXIMATIONS is frozen to prevent concurrency issues" do assert I18n::Backend::Transliterator::HashTransliterator::DEFAULT_APPROXIMATIONS.frozen? end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/fallbacks_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/fallbacks_test.rb
require 'test_helper' class I18nBackendFallbacksTranslateTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Fallbacks end def setup super I18n.backend = Backend.new store_translations(:en, :foo => 'Foo in :en', :bar => 'Bar in :en', :buz => 'Buz in :en', :interpolate => 'Interpolate %{value}') store_translations(:de, :bar => 'Bar in :de', :baz => 'Baz in :de') store_translations(:'de-DE', :baz => 'Baz in :de-DE') store_translations(:'pt-BR', :baz => 'Baz in :pt-BR') end test "still returns an existing translation as usual" do assert_equal 'Foo in :en', I18n.t(:foo, :locale => :en) assert_equal 'Bar in :de', I18n.t(:bar, :locale => :de) assert_equal 'Baz in :de-DE', I18n.t(:baz, :locale => :'de-DE') end test "returns interpolated value if no key provided" do assert_equal 'Interpolate %{value}', I18n.t(:interpolate) end test "returns the :en translation for a missing :de translation" do assert_equal 'Foo in :en', I18n.t(:foo, :locale => :de) end test "returns the :de translation for a missing :'de-DE' translation" do assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE') end test "returns the :en translation for translation missing in both :de and :'de-De'" do assert_equal 'Buz in :en', I18n.t(:buz, :locale => :'de-DE') end test "returns the :de translation for a missing :'de-DE' when :default is a String" do assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE', :default => "Default Bar") assert_equal "Default Bar", I18n.t(:missing_bar, :locale => :'de-DE', :default => "Default Bar") end test "returns the :de translation for a missing :'de-DE' when defaults is a Symbol (which exists in :en)" do assert_equal "Bar in :de", I18n.t(:bar, :locale => :'de-DE', :default => [:buz]) end test "returns the :'de-DE' default :baz translation for a missing :'de-DE' (which exists in :de)" do assert_equal "Baz in :de-DE", I18n.t(:bar, :locale => :'de-DE', :default => [:baz]) end test "returns the :de translation for a missing :'de-DE' when :default is a Proc" do assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE', :default => Proc.new { "Default Bar" }) assert_equal "Default Bar", I18n.t(:missing_bar, :locale => :'de-DE', :default => Proc.new { "Default Bar" }) end test "returns the :de translation for a missing :'de-DE' when :default is a Hash" do assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE', :default => {}) assert_equal({}, I18n.t(:missing_bar, :locale => :'de-DE', :default => {})) end test "returns the :de translation for a missing :'de-DE' when :default is nil" do assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE', :default => nil) assert_nil I18n.t(:missing_bar, :locale => :'de-DE', :default => nil) end test "returns the translation missing message if the default is also missing" do assert_equal 'translation missing: de-DE.missing_bar', I18n.t(:missing_bar, :locale => :'de-DE', :default => [:missing_baz]) end test "returns the :'de-DE' default :baz translation for a missing :'de-DE' when defaults contains Symbol" do assert_equal 'Baz in :de-DE', I18n.t(:missing_foo, :locale => :'de-DE', :default => [:baz, "Default Bar"]) end test "returns the defaults translation for a missing :'de-DE' when defaults contains a String or Proc before Symbol" do assert_equal "Default Bar", I18n.t(:missing_foo, :locale => :'de-DE', :default => [:missing_bar, "Default Bar", :baz]) assert_equal "Default Bar", I18n.t(:missing_foo, :locale => :'de-DE', :default => [:missing_bar, Proc.new { "Default Bar" }, :baz]) end test "returns the default translation for a missing :'de-DE' and existing :de when default is a Hash" do assert_equal 'Default 6 Bars', I18n.t(:missing_foo, :locale => :'de-DE', :default => [:missing_bar, {:other => "Default %{count} Bars"}, "Default Bar"], :count => 6) end test "returns the default translation for a missing :de translation even when default is a String when fallback is disabled" do assert_equal 'Default String', I18n.t(:foo, :locale => :de, :default => 'Default String', :fallback => false) end test "raises I18n::MissingTranslationData exception when fallback is disabled even when fallback translation exists" do assert_raise(I18n::MissingTranslationData) { I18n.t(:foo, :locale => :de, :fallback => false, :raise => true) } end test "raises I18n::MissingTranslationData exception when no translation was found" do assert_raise(I18n::MissingTranslationData) { I18n.t(:faa, :locale => :en, :raise => true) } assert_raise(I18n::MissingTranslationData) { I18n.t(:faa, :locale => :de, :raise => true) } end test "should ensure that default is not splitted on new line char" do assert_equal "Default \n Bar", I18n.t(:missing_bar, :default => "Default \n Bar") end test "should not raise error when enforce_available_locales is true, :'pt' is missing and default is a Symbol" do I18n.enforce_available_locales = true begin assert_equal 'Foo', I18n.t(:'model.attrs.foo', :locale => :'pt-BR', :default => [:'attrs.foo', "Foo"]) ensure I18n.enforce_available_locales = false end end end class I18nBackendFallbacksLocalizeTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Fallbacks end def setup super I18n.backend = Backend.new store_translations(:en, :date => { :formats => { :en => 'en' }, :day_names => %w(Sunday) }) store_translations(:de, :date => { :formats => { :de => 'de' } }) end test "still uses an existing format as usual" do assert_equal 'en', I18n.l(Date.today, :format => :en, :locale => :en) end test "looks up and uses a fallback locale's format for a key missing in the given locale (1)" do assert_equal 'en', I18n.l(Date.today, :format => :en, :locale => :de) end test "looks up and uses a fallback locale's format for a key missing in the given locale (2)" do assert_equal 'de', I18n.l(Date.today, :format => :de, :locale => :'de-DE') end test "still uses an existing day name translation as usual" do assert_equal 'Sunday', I18n.l(Date.new(2010, 1, 3), :format => '%A', :locale => :en) end test "uses a fallback locale's translation for a key missing in the given locale" do assert_equal 'Sunday', I18n.l(Date.new(2010, 1, 3), :format => '%A', :locale => :de) end end class I18nBackendFallbacksWithChainTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Fallbacks end class Chain < I18n::Backend::Chain include I18n::Backend::Fallbacks end def setup super backend = Backend.new backend.store_translations(:de, :foo => 'FOO') backend.store_translations(:'pt-BR', :foo => 'Baz in :pt-BR') I18n.backend = Chain.new(I18n::Backend::Simple.new, backend) end test "falls back from de-DE to de when there is no translation for de-DE available" do assert_equal 'FOO', I18n.t(:foo, :locale => :'de-DE') end test "falls back from de-DE to de when there is no translation for de-DE available when using arrays, too" do assert_equal ['FOO', 'FOO'], I18n.t([:foo, :foo], :locale => :'de-DE') end test "should not raise error when enforce_available_locales is true, :'pt' is missing and default is a Symbol" do I18n.enforce_available_locales = true begin assert_equal 'Foo', I18n.t(:'model.attrs.foo', :locale => :'pt-BR', :default => [:'attrs.foo', "Foo"]) ensure I18n.enforce_available_locales = false end end end class I18nBackendFallbacksExistsTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Fallbacks end def setup super I18n.backend = Backend.new store_translations(:en, :foo => 'Foo in :en', :bar => 'Bar in :en') store_translations(:de, :bar => 'Bar in :de') store_translations(:'de-DE', :baz => 'Baz in :de-DE') end test "exists? given an existing key will return true" do assert_equal true, I18n.exists?(:foo) end test "exists? given a non-existing key will return false" do assert_equal false, I18n.exists?(:bogus) end test "exists? given an existing key and an existing locale will return true" do assert_equal true, I18n.exists?(:foo, :en) assert_equal true, I18n.exists?(:bar, :de) end test "exists? given a non-existing key and an existing locale will return false" do assert_equal false, I18n.exists?(:bogus, :en) assert_equal false, I18n.exists?(:bogus, :de) end test "exists? should return true given a key which is missing from the given locale and exists in a fallback locale" do assert_equal true, I18n.exists?(:foo, :de) assert_equal true, I18n.exists?(:foo, :'de-DE') end test "exists? should return false given a key which is missing from the given locale and all its fallback locales" do assert_equal false, I18n.exists?(:baz, :de) assert_equal false, I18n.exists?(:bogus, :'de-DE') end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/memoize_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/memoize_test.rb
require 'test_helper' # TODO: change back to "require 'backend/simple'" when dropping support to Ruby 1.8.7. require File.expand_path('../simple_test', __FILE__) class I18nBackendMemoizeTest < I18nBackendSimpleTest module MemoizeSpy attr_accessor :spy_calls def available_locales self.spy_calls = (self.spy_calls || 0) + 1 super end end class MemoizeBackend < I18n::Backend::Simple include MemoizeSpy include I18n::Backend::Memoize end def setup super I18n.backend = MemoizeBackend.new end def test_memoizes_available_locales I18n.backend.spy_calls = 0 assert_equal I18n.available_locales, I18n.available_locales assert_equal 1, I18n.backend.spy_calls end def test_resets_available_locales_on_reload! I18n.available_locales I18n.backend.spy_calls = 0 I18n.reload! assert_equal I18n.available_locales, I18n.available_locales assert_equal 1, I18n.backend.spy_calls end def test_resets_available_locales_on_store_translations I18n.available_locales I18n.backend.spy_calls = 0 I18n.backend.store_translations(:copa, :ca => :bana) assert_equal I18n.available_locales, I18n.available_locales assert I18n.available_locales.include?(:copa) assert_equal 1, I18n.backend.spy_calls end module TestLookup def lookup(locale, key, scope = [], options = {}) keys = I18n.normalize_keys(locale, key, scope, options[:separator]) keys.inspect end end def test_lookup_concurrent_consistency backend_impl = Class.new(I18n::Backend::Simple) do include TestLookup include I18n::Backend::Memoize end backend = backend_impl.new memoized_lookup = backend.send(:memoized_lookup) assert_equal "[:foo, :scoped, :sample]", backend.translate('foo', scope = [:scoped, :sample]) results = [] 30.times.inject([]) do |memo, i| memo << Thread.new do backend.translate('bar', scope); backend.translate(:baz, scope) end end.each(&:join) memoized_lookup = backend.send(:memoized_lookup) puts memoized_lookup.inspect if $VERBOSE assert_equal 3, memoized_lookup.size, "NON-THREAD-SAFE lookup memoization backend: #{memoized_lookup.class}" # if a plain Hash is used might eventually end up in a weird (inconsistent) state end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/metadata_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/metadata_test.rb
require 'test_helper' class I18nBackendMetadataTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Metadata end def setup super I18n.backend = Backend.new store_translations(:en, :foo => 'Hi %{name}') end test "translation strings carry metadata" do translation = I18n.t(:foo, :name => 'David') assert translation.respond_to?(:translation_metadata) assert translation.translation_metadata.is_a?(Hash) end test "translate adds the locale to metadata on Strings" do assert_equal :en, I18n.t(:foo, :name => 'David', :locale => :en).translation_metadata[:locale] end test "translate adds the key to metadata on Strings" do assert_equal :foo, I18n.t(:foo, :name => 'David').translation_metadata[:key] end test "translate adds the default to metadata on Strings" do assert_equal 'bar', I18n.t(:foo, :default => 'bar', :name => '').translation_metadata[:default] end test "translation adds the interpolation values to metadata on Strings" do assert_equal({:name => 'David'}, I18n.t(:foo, :name => 'David').translation_metadata[:values]) end test "interpolation adds the original string to metadata on Strings" do assert_equal('Hi %{name}', I18n.t(:foo, :name => 'David').translation_metadata[:original]) end test "pluralization adds the count to metadata on Strings" do assert_equal(1, I18n.t(:missing, :count => 1, :default => { :one => 'foo' }).translation_metadata[:count]) end test "metadata works with frozen values" do assert_equal(1, I18n.t(:missing, :count => 1, :default => 'foo'.freeze).translation_metadata[:count]) end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/key_value_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/key_value_test.rb
require 'test_helper' class I18nBackendKeyValueTest < I18n::TestCase def setup_backend!(subtree=true) I18n.backend = I18n::Backend::KeyValue.new({}, subtree) store_translations(:en, :foo => { :bar => 'bar', :baz => 'baz' }) end def assert_flattens(expected, nested, escape=true, subtree=true) assert_equal expected, I18n.backend.flatten_translations("en", nested, escape, subtree) end test "hash flattening works" do setup_backend! assert_flattens( {:a=>'a', :b=>{:c=>'c', :d=>'d', :f=>{:x=>'x'}}, :"b.f" => {:x=>"x"}, :"b.c"=>"c", :"b.f.x"=>"x", :"b.d"=>"d"}, {:a=>'a', :b=>{:c=>'c', :d=>'d', :f=>{:x=>'x'}}} ) assert_flattens({:a=>{:b =>['a', 'b']}, :"a.b"=>['a', 'b']}, {:a=>{:b =>['a', 'b']}}) assert_flattens({:"a\001b" => "c"}, {:"a.b" => "c"}) assert_flattens({:"a.b"=>['a', 'b']}, {:a=>{:b =>['a', 'b']}}, true, false) assert_flattens({:"a.b" => "c"}, {:"a.b" => "c"}, false) end test "store_translations handle subtrees by default" do setup_backend! assert_equal({ :bar => 'bar', :baz => 'baz' }, I18n.t("foo")) end test "store_translations merge subtrees accordingly" do setup_backend! store_translations(:en, :foo => { :baz => "BAZ"}) assert_equal('BAZ', I18n.t("foo.baz")) assert_equal({ :bar => 'bar', :baz => 'BAZ' }, I18n.t("foo")) end test "store_translations does not handle subtrees if desired" do setup_backend!(false) assert_raise I18n::MissingTranslationData do I18n.t("foo", :raise => true) end end test "subtrees enabled: given incomplete pluralization data it raises I18n::InvalidPluralizationData" do setup_backend! store_translations(:en, :bar => { :one => "One" }) assert_raise(I18n::InvalidPluralizationData) { I18n.t(:bar, :count => 2) } end test "subtrees disabled: given incomplete pluralization data it returns an error message" do setup_backend!(false) store_translations(:en, :bar => { :one => "One" }) assert_equal "translation missing: en.bar", I18n.t(:bar, :count => 2) end test "translate handles subtrees for pluralization" do setup_backend!(false) store_translations(:en, :bar => { :one => "One" }) assert_equal("One", I18n.t("bar", :count => 1)) end end if I18n::TestCase.key_value?
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/interpolation_compiler_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/interpolation_compiler_test.rb
require 'test_helper' class InterpolationCompilerTest < I18n::TestCase Compiler = I18n::Backend::InterpolationCompiler::Compiler def compile_and_interpolate(str, values = {}) Compiler.compile_if_an_interpolation(str).i18n_interpolate(values) end def assert_escapes_interpolation_key(expected, malicious_str) assert_equal(expected, Compiler.send(:escape_key_sym, malicious_str)) end def test_escape_key_properly_escapes assert_escapes_interpolation_key ':"\""', '"' assert_escapes_interpolation_key ':"\\\\"', '\\' assert_escapes_interpolation_key ':"\\\\\""', '\\"' assert_escapes_interpolation_key ':"\#{}"', '#{}' assert_escapes_interpolation_key ':"\\\\\#{}"', '\#{}' end def assert_escapes_plain_string(expected, plain_str) assert_equal expected, Compiler.send(:escape_plain_str, plain_str) end def test_escape_plain_string_properly_escapes assert_escapes_plain_string '\\"', '"' assert_escapes_plain_string '\'', '\'' assert_escapes_plain_string '\\#', '#' assert_escapes_plain_string '\\#{}', '#{}' assert_escapes_plain_string '\\\\\\"','\\"' end def test_non_interpolated_strings_or_arrays_dont_get_compiled ['abc', '\\{a}}', '{a}}', []].each do |obj| Compiler.compile_if_an_interpolation(obj) assert_equal false, obj.respond_to?(:i18n_interpolate) end end def test_interpolated_string_gets_compiled assert_equal '-A-', compile_and_interpolate('-%{a}-', :a => 'A') end def assert_handles_key(str, key) assert_equal 'A', compile_and_interpolate(str, key => 'A') end def test_compiles_fancy_keys assert_handles_key('%{\}', :'\\' ) assert_handles_key('%{#}', :'#' ) assert_handles_key('%{#{}', :'#{' ) assert_handles_key('%{#$SAFE}', :'#$SAFE') assert_handles_key('%{\000}', :'\000' ) assert_handles_key('%{\'}', :'\'' ) assert_handles_key('%{\'\'}', :'\'\'' ) assert_handles_key('%{a.b}', :'a.b' ) assert_handles_key('%{ }', :' ' ) assert_handles_key('%{:}', :':' ) assert_handles_key("%{:''}", :":''" ) assert_handles_key('%{:"}', :':"' ) end def test_str_containing_only_escaped_interpolation_is_handled_correctly assert_equal 'abc %{x}', compile_and_interpolate('abc %%{x}') end def test_handles_weird_strings assert_equal '#{} a', compile_and_interpolate('#{} %{a}', :a => 'a') assert_equal '"#{abc}"', compile_and_interpolate('"#{ab%{a}c}"', :a => '' ) assert_equal 'a}', compile_and_interpolate('%{{a}}', :'{a' => 'a') assert_equal '"', compile_and_interpolate('"%{a}', :a => '' ) assert_equal 'a%{a}', compile_and_interpolate('%{a}%%{a}', :a => 'a') assert_equal '%%{a}', compile_and_interpolate('%%%{a}') assert_equal '\";eval("a")', compile_and_interpolate('\";eval("%{a}")', :a => 'a') assert_equal '\";eval("a")', compile_and_interpolate('\";eval("a")%{a}', :a => '' ) assert_equal "\na", compile_and_interpolate("\n%{a}", :a => 'a') end def test_raises_exception_when_argument_is_missing assert_raise(I18n::MissingInterpolationArgument) do compile_and_interpolate('%{first} %{last}', :first => 'first') end end def test_custom_missing_interpolation_argument_handler old_handler = I18n.config.missing_interpolation_argument_handler I18n.config.missing_interpolation_argument_handler = lambda do |key, values, string| "missing key is #{key}, values are #{values.inspect}, given string is '#{string}'" end assert_equal %|first missing key is last, values are {:first=>"first"}, given string is '%{first} %{last}'|, compile_and_interpolate('%{first} %{last}', :first => 'first') ensure I18n.config.missing_interpolation_argument_handler = old_handler end end class I18nBackendInterpolationCompilerTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::InterpolationCompiler end include I18n::Tests::Interpolation def setup I18n.backend = Backend.new super end # pre-compile default strings to make sure we are testing I18n::Backend::InterpolationCompiler def interpolate(*args) options = args.last.kind_of?(Hash) ? args.last : {} if default_str = options[:default] I18n::Backend::InterpolationCompiler::Compiler.compile_if_an_interpolation(default_str) end super end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/pluralization_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/pluralization_test.rb
require 'test_helper' class I18nBackendPluralizationTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Pluralization include I18n::Backend::Fallbacks end def setup super I18n.backend = Backend.new @rule = lambda { |n| n == 1 ? :one : n == 0 || (2..10).include?(n % 100) ? :few : (11..19).include?(n % 100) ? :many : :other } store_translations(:xx, :i18n => { :plural => { :rule => @rule } }) @entry = { :zero => 'zero', :one => 'one', :few => 'few', :many => 'many', :other => 'other' } end test "pluralization picks a pluralizer from :'i18n.pluralize'" do assert_equal @rule, I18n.backend.send(:pluralizer, :xx) end test "pluralization picks :one for 1" do assert_equal 'one', I18n.t(:count => 1, :default => @entry, :locale => :xx) end test "pluralization picks :few for 2" do assert_equal 'few', I18n.t(:count => 2, :default => @entry, :locale => :xx) end test "pluralization picks :many for 11" do assert_equal 'many', I18n.t(:count => 11, :default => @entry, :locale => :xx) end test "pluralization picks zero for 0 if the key is contained in the data" do assert_equal 'zero', I18n.t(:count => 0, :default => @entry, :locale => :xx) end test "pluralization picks few for 0 if the key is not contained in the data" do @entry.delete(:zero) assert_equal 'few', I18n.t(:count => 0, :default => @entry, :locale => :xx) end test "Fallbacks can pick up rules from fallback locales, too" do assert_equal @rule, I18n.backend.send(:pluralizer, :'xx-XX') end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/simple_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/simple_test.rb
require 'test_helper' class I18nBackendSimpleTest < I18n::TestCase def setup super I18n.backend = I18n::Backend::Simple.new I18n.load_path = [locales_dir + '/en.yml'] end # useful because this way we can use the backend with no key for interpolation/pluralization test "simple backend translate: given nil as a key it still interpolations the default value" do assert_equal "Hi David", I18n.t(nil, :default => "Hi %{name}", :name => "David") end # loading translations test "simple load_translations: given an unknown file type it raises I18n::UnknownFileType" do assert_raise(I18n::UnknownFileType) { I18n.backend.load_translations("#{locales_dir}/en.xml") } end test "simple load_translations: given a Ruby file name it does not raise anything" do assert_nothing_raised { I18n.backend.load_translations("#{locales_dir}/en.rb") } end test "simple load_translations: given no argument, it uses I18n.load_path" do I18n.backend.load_translations assert_equal({ :en => { :foo => { :bar => 'baz' } } }, I18n.backend.send(:translations)) end test "simple load_rb: loads data from a Ruby file" do data = I18n.backend.send(:load_rb, "#{locales_dir}/en.rb") assert_equal({ :en => { :fuh => { :bah => 'bas' } } }, data) end test "simple load_yml: loads data from a YAML file" do data = I18n.backend.send(:load_yml, "#{locales_dir}/en.yml") assert_equal({ 'en' => { 'foo' => { 'bar' => 'baz' } } }, data) end test "simple load_translations: loads data from known file formats" do I18n.backend = I18n::Backend::Simple.new I18n.backend.load_translations("#{locales_dir}/en.rb", "#{locales_dir}/en.yml") expected = { :en => { :fuh => { :bah => "bas" }, :foo => { :bar => "baz" } } } assert_equal expected, translations end test "simple load_translations: given file names as array it does not raise anything" do assert_nothing_raised { I18n.backend.load_translations(["#{locales_dir}/en.rb", "#{locales_dir}/en.yml"]) } end # storing translations test "simple store_translations: stores translations, ... no, really :-)" do store_translations :'en', :foo => 'bar' assert_equal Hash[:'en', {:foo => 'bar'}], translations end test "simple store_translations: deep_merges with existing translations" do store_translations :'en', :foo => {:bar => 'bar'} store_translations :'en', :foo => {:baz => 'baz'} assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], translations end test "simple store_translations: converts the given locale to a Symbol" do store_translations 'en', :foo => 'bar' assert_equal Hash[:'en', {:foo => 'bar'}], translations end test "simple store_translations: converts keys to Symbols" do store_translations 'en', 'foo' => {'bar' => 'bar', 'baz' => 'baz'} assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], translations end test "simple store_translations: do not store translations unavailable locales if enforce_available_locales is true" do begin I18n.enforce_available_locales = true I18n.available_locales = [:en, :es] store_translations(:fr, :foo => {:bar => 'barfr', :baz => 'bazfr'}) store_translations(:es, :foo => {:bar => 'bares', :baz => 'bazes'}) assert_nil translations[:fr] assert_equal Hash[:foo, {:bar => 'bares', :baz => 'bazes'}], translations[:es] ensure I18n.config.enforce_available_locales = false end end test "simple store_translations: store translations for unavailable locales if enforce_available_locales is false" do I18n.available_locales = [:en, :es] store_translations(:fr, :foo => {:bar => 'barfr', :baz => 'bazfr'}) assert_equal Hash[:foo, {:bar => 'barfr', :baz => 'bazfr'}], translations[:fr] end # reloading translations test "simple reload_translations: unloads translations" do I18n.backend.reload! assert_nil translations end test "simple reload_translations: uninitializes the backend" do I18n.backend.reload! assert_equal false, I18n.backend.initialized? end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/chain_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/chain_test.rb
require 'test_helper' class I18nBackendChainTest < I18n::TestCase def setup super @first = backend(:en => { :foo => 'Foo', :formats => { :short => 'short', :subformats => {:short => 'short'}, }, :plural_1 => { :one => '%{count}' }, :dates => {:a => "A"} }) @second = backend(:en => { :bar => 'Bar', :formats => { :long => 'long', :subformats => {:long => 'long'}, }, :plural_2 => { :one => 'one' }, :dates => {:a => "B", :b => "B"} }) @chain = I18n.backend = I18n::Backend::Chain.new(@first, @second) end test "looks up translations from the first chained backend" do assert_equal 'Foo', @first.send(:translations)[:en][:foo] assert_equal 'Foo', I18n.t(:foo) end test "looks up translations from the second chained backend" do assert_equal 'Bar', @second.send(:translations)[:en][:bar] assert_equal 'Bar', I18n.t(:bar) end test "defaults only apply to lookups on the last backend in the chain" do assert_equal 'Foo', I18n.t(:foo, :default => 'Bah') assert_equal 'Bar', I18n.t(:bar, :default => 'Bah') assert_equal 'Bah', I18n.t(:bah, :default => 'Bah') # default kicks in only here end test "default" do assert_equal 'Fuh', I18n.t(:default => 'Fuh') assert_equal 'Zero', I18n.t(:default => { :zero => 'Zero' }, :count => 0) assert_equal({ :zero => 'Zero' }, I18n.t(:default => { :zero => 'Zero' })) assert_equal 'Foo', I18n.t(:default => :foo) end test 'default is returned if translation is missing' do assert_equal({}, I18n.t(:'i18n.transliterate.rule', :locale => 'en', :default => {})) end test "namespace lookup collects results from all backends and merges deep hashes" do assert_equal({:long=>"long", :subformats=>{:long=>"long", :short=>"short"}, :short=>"short"}, I18n.t(:formats)) end test "namespace lookup collects results from all backends and lets leftmost backend take priority" do assert_equal({ :a => "A", :b => "B" }, I18n.t(:dates)) end test "namespace lookup with only the first backend returning a result" do assert_equal({ :one => '%{count}' }, I18n.t(:plural_1)) end test "pluralization still works" do assert_equal '1', I18n.t(:plural_1, :count => 1) assert_equal 'one', I18n.t(:plural_2, :count => 1) end test "bulk lookup collects results from all backends" do assert_equal ['Foo', 'Bar'], I18n.t([:foo, :bar]) assert_equal ['Foo', 'Bar', 'Bah'], I18n.t([:foo, :bar, :bah], :default => 'Bah') assert_equal [{ :long=>"long", :subformats=>{:long=>"long", :short=>"short"}, :short=>"short"}, {:one=>"one"}, "Bah"], I18n.t([:formats, :plural_2, :bah], :default => 'Bah') end test "store_translations options are not dropped while transfering to backend" do @first.expects(:store_translations).with(:foo, {:bar => :baz}, {:option => 'persists'}) I18n.backend.store_translations :foo, {:bar => :baz}, {:option => 'persists'} end protected def backend(translations) backend = I18n::Backend::Simple.new translations.each { |locale, data| backend.store_translations(locale, data) } backend end end class I18nBackendChainWithKeyValueTest < I18n::TestCase def setup_backend!(subtrees = true) first = I18n::Backend::KeyValue.new({}, subtrees) first.store_translations(:en, :plural_1 => { :one => '%{count}' }) second = I18n::Backend::Simple.new second.store_translations(:en, :plural_2 => { :one => 'one' }) I18n.backend = I18n::Backend::Chain.new(first, second) end test "subtrees enabled: looks up pluralization translations from the first chained backend" do setup_backend! assert_equal '1', I18n.t(:plural_1, count: 1) end test "subtrees disabled: looks up pluralization translations from the first chained backend" do setup_backend!(false) assert_equal '1', I18n.t(:plural_1, count: 1) end test "subtrees enabled: looks up translations from the second chained backend" do setup_backend! assert_equal 'one', I18n.t(:plural_2, count: 1) end test "subtrees disabled: looks up translations from the second chained backend" do setup_backend!(false) assert_equal 'one', I18n.t(:plural_2, count: 1) end end if I18n::TestCase.key_value?
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/cascade_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/cascade_test.rb
require 'test_helper' class I18nBackendCascadeTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Cascade end def setup super I18n.backend = Backend.new store_translations(:en, :foo => 'foo', :bar => { :baz => 'baz' }) @cascade_options = { :step => 1, :offset => 1, :skip_root => false } end def lookup(key, options = {}) I18n.t(key, options.merge(:cascade => @cascade_options)) end test "still returns an existing translation as usual" do assert_equal 'foo', lookup(:foo) assert_equal 'baz', lookup(:'bar.baz') end test "falls back by cutting keys off the end of the scope" do assert_equal 'foo', lookup(:foo, :scope => :'missing') assert_equal 'foo', lookup(:foo, :scope => :'missing.missing') assert_equal 'baz', lookup(:baz, :scope => :'bar.missing') assert_equal 'baz', lookup(:baz, :scope => :'bar.missing.missing') end test "raises I18n::MissingTranslationData exception when no translation was found" do assert_raise(I18n::MissingTranslationData) { lookup(:'foo.missing', :raise => true) } assert_raise(I18n::MissingTranslationData) { lookup(:'bar.baz.missing', :raise => true) } assert_raise(I18n::MissingTranslationData) { lookup(:'missing.bar.baz', :raise => true) } end test "cascades before evaluating the default" do assert_equal 'foo', lookup(:foo, :scope => :missing, :default => 'default') end test "cascades defaults, too" do assert_equal 'foo', lookup(nil, :default => [:'missing.missing', :'missing.foo']) end test "works with :offset => 2 and a single key" do @cascade_options[:offset] = 2 lookup(:foo) end test "assemble required fallbacks for ActiveRecord validation messages" do store_translations(:en, :errors => { :odd => 'errors.odd', :reply => { :title => { :blank => 'errors.reply.title.blank' }, :taken => 'errors.reply.taken' }, :topic => { :title => { :format => 'errors.topic.title.format' }, :length => 'errors.topic.length' } } ) assert_equal 'errors.reply.title.blank', lookup(:'errors.reply.title.blank', :default => :'errors.topic.title.blank') assert_equal 'errors.reply.taken', lookup(:'errors.reply.title.taken', :default => :'errors.topic.title.taken') assert_equal 'errors.topic.title.format', lookup(:'errors.reply.title.format', :default => :'errors.topic.title.format') assert_equal 'errors.topic.length', lookup(:'errors.reply.title.length', :default => :'errors.topic.title.length') assert_equal 'errors.odd', lookup(:'errors.reply.title.odd', :default => :'errors.topic.title.odd') end test "assemble action view translation helper lookup cascade" do @cascade_options[:offset] = 2 store_translations(:en, :menu => { :show => 'menu.show' }, :namespace => { :menu => { :new => 'namespace.menu.new' }, :controller => { :menu => { :edit => 'namespace.controller.menu.edit' }, :action => { :menu => { :destroy => 'namespace.controller.action.menu.destroy' } } } } ) assert_equal 'menu.show', lookup(:'namespace.controller.action.menu.show') assert_equal 'namespace.menu.new', lookup(:'namespace.controller.action.menu.new') assert_equal 'namespace.controller.menu.edit', lookup(:'namespace.controller.action.menu.edit') assert_equal 'namespace.controller.action.menu.destroy', lookup(:'namespace.controller.action.menu.destroy') end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/exceptions_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/exceptions_test.rb
require 'test_helper' class I18nBackendExceptionsTest < I18n::TestCase def setup super I18n.backend = I18n::Backend::Simple.new end test "throw message: MissingTranslation message from #translate includes the given scope and full key" do exception = catch(:exception) do I18n.t(:'baz.missing', :scope => :'foo.bar', :throw => true) end assert_equal "translation missing: en.foo.bar.baz.missing", exception.message end test "exceptions: MissingTranslationData message from #translate includes the given scope and full key" do begin I18n.t(:'baz.missing', :scope => :'foo.bar', :raise => true) rescue I18n::MissingTranslationData => exception end assert_equal "translation missing: en.foo.bar.baz.missing", exception.message end test "exceptions: MissingTranslationData message from #localize includes the given scope and full key" do begin I18n.l(Time.now, :format => :foo) rescue I18n::MissingTranslationData => exception end assert_equal "translation missing: en.time.formats.foo", exception.message end test "exceptions: MissingInterpolationArgument message includes missing key, provided keys and full string" do exception = I18n::MissingInterpolationArgument.new('key', {:this => 'was given'}, 'string') assert_equal 'missing interpolation argument "key" in "string" ({:this=>"was given"} given)', exception.message end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/cache_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/backend/cache_test.rb
require 'test_helper' require 'digest/md5' begin require 'active_support' rescue LoadError $stderr.puts "Skipping cache tests using ActiveSupport" else class I18nBackendCacheTest < I18n::TestCase class Backend < I18n::Backend::Simple include I18n::Backend::Cache end def setup I18n.backend = Backend.new super I18n.cache_store = ActiveSupport::Cache.lookup_store(:memory_store) I18n.cache_key_digest = nil end def teardown super I18n.cache_store = nil end test "it uses the cache" do assert I18n.cache_store.is_a?(ActiveSupport::Cache::MemoryStore) end test "translate hits the backend and caches the response" do I18n.backend.expects(:lookup).returns('Foo') assert_equal 'Foo', I18n.t(:foo) I18n.backend.expects(:lookup).never assert_equal 'Foo', I18n.t(:foo) I18n.backend.expects(:lookup).returns('Bar') assert_equal 'Bar', I18n.t(:bar) end test "translate returns a cached false response" do I18n.backend.expects(:lookup).never I18n.cache_store.expects(:read).returns(false) assert_equal false, I18n.t(:foo) end test "still raises MissingTranslationData but also caches it" do assert_raise(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) } assert_raise(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) } assert_equal 1, I18n.cache_store.instance_variable_get(:@data).size # I18n.backend.expects(:lookup).returns(nil) # assert_raise(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) } # I18n.backend.expects(:lookup).never # assert_raise(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) } end test "uses 'i18n' as a cache key namespace by default" do assert_equal 0, I18n.backend.send(:cache_key, :en, :foo, {}).index('i18n') end test "adds a custom cache key namespace" do with_cache_namespace('bar') do assert_equal 0, I18n.backend.send(:cache_key, :en, :foo, {}).index('i18n/bar/') end end test "adds locale and hash of key and hash of options" do options = { :bar=>1 } options_hash = RUBY_VERSION <= "1.9" ? options.inspect.hash : options.hash assert_equal "i18n//en/#{:foo.hash}/#{options_hash}", I18n.backend.send(:cache_key, :en, :foo, options) end test "cache_key uses configured digest method" do md5 = Digest::MD5.new options = { :bar=>1 } options_hash = options.inspect with_cache_key_digest(md5) do assert_equal "i18n//en/#{md5.hexdigest(:foo.to_s)}/#{md5.hexdigest(options_hash)}", I18n.backend.send(:cache_key, :en, :foo, options) end end test "keys should not be equal" do interpolation_values1 = { :foo => 1, :bar => 2 } interpolation_values2 = { :foo => 2, :bar => 1 } key1 = I18n.backend.send(:cache_key, :en, :some_key, interpolation_values1) key2 = I18n.backend.send(:cache_key, :en, :some_key, interpolation_values2) assert key1 != key2 end protected def with_cache_namespace(namespace) I18n.cache_namespace = namespace yield I18n.cache_namespace = nil end def with_cache_key_digest(digest) I18n.cache_key_digest = digest yield I18n.cache_key_digest = nil end end end # AS cache check
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/locale/fallbacks_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/locale/fallbacks_test.rb
require 'test_helper' include I18n::Locale class I18nFallbacksDefaultsTest < I18n::TestCase test "defaults reflect the I18n.default_locale if no default has been set manually" do I18n.default_locale = :'en-US' fallbacks = Fallbacks.new assert_equal [:'en-US', :en], fallbacks.defaults end test "defaults reflect a manually passed default locale if any" do fallbacks = Fallbacks.new(:'fi-FI') assert_equal [:'fi-FI', :fi], fallbacks.defaults I18n.default_locale = :'de-DE' assert_equal [:'fi-FI', :fi], fallbacks.defaults end test "defaults allows to set multiple defaults" do fallbacks = Fallbacks.new(:'fi-FI', :'se-FI') assert_equal [:'fi-FI', :fi, :'se-FI', :se], fallbacks.defaults end end class I18nFallbacksComputationTest < I18n::TestCase def setup super @fallbacks = Fallbacks.new(:'en-US') end test "with no mappings defined it returns [:es, :en-US] for :es" do assert_equal [:es, :"en-US", :en], @fallbacks[:es] end test "with no mappings defined it returns [:es-ES, :es, :en-US] for :es-ES" do assert_equal [:"es-ES", :es, :"en-US", :en], @fallbacks[:"es-ES"] end test "with no mappings defined it returns [:es-MX, :es, :en-US] for :es-MX" do assert_equal [:"es-MX", :es, :"en-US", :en], @fallbacks[:"es-MX"] end test "with no mappings defined it returns [:es-Latn-ES, :es-Latn, :es, :en-US] for :es-Latn-ES" do assert_equal [:"es-Latn-ES", :"es-Latn", :es, :"en-US", :en], @fallbacks[:'es-Latn-ES'] end test "with no mappings defined it returns [:en, :en-US] for :en" do assert_equal [:en, :"en-US"], @fallbacks[:en] end test "with no mappings defined it returns [:en-US, :en] for :en-US (special case: locale == default)" do assert_equal [:"en-US", :en], @fallbacks[:"en-US"] end # Most people who speak Catalan also live in Spain, so it is safe to assume # that they also speak Spanish as spoken in Spain. test "with a Catalan mapping defined it returns [:ca, :es-ES, :es, :en-US] for :ca" do @fallbacks.map(:ca => :"es-ES") assert_equal [:ca, :"es-ES", :es, :"en-US", :en], @fallbacks[:ca] end test "with a Catalan mapping defined it returns [:ca-ES, :ca, :es-ES, :es, :en-US] for :ca-ES" do @fallbacks.map(:ca => :"es-ES") assert_equal [:"ca-ES", :ca, :"es-ES", :es, :"en-US", :en], @fallbacks[:"ca-ES"] end # People who speak Arabic as spoken in Palestine often times also speak # Hebrew as spoken in Israel. However it is in no way safe to assume that # everybody who speaks Arabic also speaks Hebrew. test "with a Hebrew mapping defined it returns [:ar, :en-US] for :ar" do @fallbacks.map(:"ar-PS" => :"he-IL") assert_equal [:ar, :"en-US", :en], @fallbacks[:ar] end test "with a Hebrew mapping defined it returns [:ar-EG, :ar, :en-US] for :ar-EG" do @fallbacks.map(:"ar-PS" => :"he-IL") assert_equal [:"ar-EG", :ar, :"en-US", :en], @fallbacks[:"ar-EG"] end test "with a Hebrew mapping defined it returns [:ar-PS, :ar, :he-IL, :he, :en-US] for :ar-PS" do @fallbacks.map(:"ar-PS" => :"he-IL") assert_equal [:"ar-PS", :ar, :"he-IL", :he, :"en-US", :en], @fallbacks[:"ar-PS"] end # Sami people live in several scandinavian countries. In Finnland many people # know Swedish and Finnish. Thus, it can be assumed that Sami living in # Finnland also speak Swedish and Finnish. test "with a Sami mapping defined it returns [:sms-FI, :sms, :se-FI, :se, :fi-FI, :fi, :en-US] for :sms-FI" do @fallbacks.map(:sms => [:"se-FI", :"fi-FI"]) assert_equal [:"sms-FI", :sms, :"se-FI", :se, :"fi-FI", :fi, :"en-US", :en], @fallbacks[:"sms-FI"] end # Austrian people understand German as spoken in Germany test "with a German mapping defined it returns [:de, :en-US] for de" do @fallbacks.map(:"de-AT" => :"de-DE") assert_equal [:de, :"en-US", :en], @fallbacks[:"de"] end test "with a German mapping defined it returns [:de-DE, :de, :en-US] for de-DE" do @fallbacks.map(:"de-AT" => :"de-DE") assert_equal [:"de-DE", :de, :"en-US", :en], @fallbacks[:"de-DE"] end test "with a German mapping defined it returns [:de-AT, :de, :de-DE, :en-US] for de-AT" do @fallbacks.map(:"de-AT" => :"de-DE") assert_equal [:"de-AT", :de, :"de-DE", :"en-US", :en], @fallbacks[:"de-AT"] end # Mapping :de => :en, :he => :en test "with a mapping :de => :en, :he => :en defined it returns [:de, :en] for :de" do assert_equal [:de, :"en-US", :en], @fallbacks[:de] end test "with a mapping :de => :en, :he => :en defined it [:he, :en] for :de" do assert_equal [:he, :"en-US", :en], @fallbacks[:he] end # Test allowing mappings that fallback to each other test "with :no => :nb, :nb => :no defined :no returns [:no, :nb, :en-US, :en]" do @fallbacks.map(:no => :nb, :nb => :no) assert_equal [:no, :nb, :"en-US", :en], @fallbacks[:no] end test "with :no => :nb, :nb => :no defined :nb returns [:nb, :no, :en-US, :en]" do @fallbacks.map(:no => :nb, :nb => :no) assert_equal [:nb, :no, :"en-US", :en], @fallbacks[:nb] end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/locale/tag/rfc4646_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/locale/tag/rfc4646_test.rb
# encoding: utf-8 require 'test_helper' class I18nLocaleTagRfc4646ParserTest < I18n::TestCase include I18n::Locale test "Rfc4646::Parser given a valid tag 'de' returns an array of subtags" do assert_equal ['de', nil, nil, nil, nil, nil, nil], Tag::Rfc4646::Parser.match('de') end test "Rfc4646::Parser given a valid tag 'de-DE' returns an array of subtags" do assert_equal ['de', nil, 'DE', nil, nil, nil, nil], Tag::Rfc4646::Parser.match('de-DE') end test "Rfc4646::Parser given a valid lowercase tag 'de-latn-de-variant-x-phonebk' returns an array of subtags" do assert_equal ['de', 'latn', 'de', 'variant', nil, 'x-phonebk', nil], Tag::Rfc4646::Parser.match('de-latn-de-variant-x-phonebk') end test "Rfc4646::Parser given a valid uppercase tag 'DE-LATN-DE-VARIANT-X-PHONEBK' returns an array of subtags" do assert_equal ['DE', 'LATN', 'DE', 'VARIANT', nil, 'X-PHONEBK', nil], Tag::Rfc4646::Parser.match('DE-LATN-DE-VARIANT-X-PHONEBK') end test "Rfc4646::Parser given an invalid tag 'a-DE' it returns false" do assert_equal false, Tag::Rfc4646::Parser.match('a-DE') end test "Rfc4646::Parser given an invalid tag 'de-419-DE' it returns false" do assert_equal false, Tag::Rfc4646::Parser.match('de-419-DE') end end # Tag for the locale 'de-Latn-DE-Variant-a-ext-x-phonebk-i-klingon' class I18nLocaleTagSubtagsTest < I18n::TestCase include I18n::Locale def setup super subtags = %w(de Latn DE variant a-ext x-phonebk i-klingon) @tag = Tag::Rfc4646.new(*subtags) end test "returns 'de' as the language subtag in lowercase" do assert_equal 'de', @tag.language end test "returns 'Latn' as the script subtag in titlecase" do assert_equal 'Latn', @tag.script end test "returns 'DE' as the region subtag in uppercase" do assert_equal 'DE', @tag.region end test "returns 'variant' as the variant subtag in lowercase" do assert_equal 'variant', @tag.variant end test "returns 'a-ext' as the extension subtag" do assert_equal 'a-ext', @tag.extension end test "returns 'x-phonebk' as the privateuse subtag" do assert_equal 'x-phonebk', @tag.privateuse end test "returns 'i-klingon' as the grandfathered subtag" do assert_equal 'i-klingon', @tag.grandfathered end test "returns a formatted tag string from #to_s" do assert_equal 'de-Latn-DE-variant-a-ext-x-phonebk-i-klingon', @tag.to_s end test "returns an array containing the formatted subtags from #to_a" do assert_equal %w(de Latn DE variant a-ext x-phonebk i-klingon), @tag.to_a end end # Tag inheritance class I18nLocaleTagSubtagsTest < I18n::TestCase test "#parent returns 'de-Latn-DE-variant-a-ext-x-phonebk' as the parent of 'de-Latn-DE-variant-a-ext-x-phonebk-i-klingon'" do tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext x-phonebk i-klingon)) assert_equal 'de-Latn-DE-variant-a-ext-x-phonebk', tag.parent.to_s end test "#parent returns 'de-Latn-DE-variant-a-ext' as the parent of 'de-Latn-DE-variant-a-ext-x-phonebk'" do tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext x-phonebk)) assert_equal 'de-Latn-DE-variant-a-ext', tag.parent.to_s end test "#parent returns 'de-Latn-DE-variant' as the parent of 'de-Latn-DE-variant-a-ext'" do tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext)) assert_equal 'de-Latn-DE-variant', tag.parent.to_s end test "#parent returns 'de-Latn-DE' as the parent of 'de-Latn-DE-variant'" do tag = Tag::Rfc4646.new(*%w(de Latn DE variant)) assert_equal 'de-Latn-DE', tag.parent.to_s end test "#parent returns 'de-Latn' as the parent of 'de-Latn-DE'" do tag = Tag::Rfc4646.new(*%w(de Latn DE)) assert_equal 'de-Latn', tag.parent.to_s end test "#parent returns 'de' as the parent of 'de-Latn'" do tag = Tag::Rfc4646.new(*%w(de Latn)) assert_equal 'de', tag.parent.to_s end # TODO RFC4647 says: "If no language tag matches the request, the "default" value is returned." # where should we set the default language? # test "#parent returns '' as the parent of 'de'" do # tag = Tag::Rfc4646.new *%w(de) # assert_equal '', tag.parent.to_s # end test "#parent returns an array of 5 parents for 'de-Latn-DE-variant-a-ext-x-phonebk-i-klingon'" do parents = %w(de-Latn-DE-variant-a-ext-x-phonebk-i-klingon de-Latn-DE-variant-a-ext-x-phonebk de-Latn-DE-variant-a-ext de-Latn-DE-variant de-Latn-DE de-Latn de) tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext x-phonebk i-klingon)) assert_equal parents, tag.self_and_parents.map(&:to_s) end test "returns an array of 5 parents for 'de-Latn-DE-variant-a-ext-x-phonebk-i-klingon'" do parents = %w(de-Latn-DE-variant-a-ext-x-phonebk-i-klingon de-Latn-DE-variant-a-ext-x-phonebk de-Latn-DE-variant-a-ext de-Latn-DE-variant de-Latn-DE de-Latn de) tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext x-phonebk i-klingon)) assert_equal parents, tag.self_and_parents.map(&:to_s) end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/locale/tag/simple_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/locale/tag/simple_test.rb
# encoding: utf-8 require 'test_helper' class I18nLocaleTagSimpleTest < I18n::TestCase include I18n::Locale test "returns 'de' as the language subtag in lowercase" do assert_equal %w(de Latn DE), Tag::Simple.new('de-Latn-DE').subtags end test "returns a formatted tag string from #to_s" do assert_equal 'de-Latn-DE', Tag::Simple.new('de-Latn-DE').to_s end test "returns an array containing the formatted subtags from #to_a" do assert_equal %w(de Latn DE), Tag::Simple.new('de-Latn-DE').to_a end # Tag inheritance test "#parent returns 'de-Latn' as the parent of 'de-Latn-DE'" do assert_equal 'de-Latn', Tag::Simple.new('de-Latn-DE').parent.to_s end test "#parent returns 'de' as the parent of 'de-Latn'" do assert_equal 'de', Tag::Simple.new('de-Latn').parent.to_s end test "#self_and_parents returns an array of 3 tags for 'de-Latn-DE'" do assert_equal %w(de-Latn-DE de-Latn de), Tag::Simple.new('de-Latn-DE').self_and_parents.map { |tag| tag.to_s} end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/test_data/locales/en.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/test_data/locales/en.rb
# encoding: utf-8 { :en => { :fuh => { :bah => "bas" } } }
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/test_data/locales/plurals.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/test_data/locales/plurals.rb
# encoding: utf-8 { :af => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :am => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :ar => { :i18n => { :plural => { :keys => [:zero, :one, :two, :few, :many, :other], :rule => lambda { |n| n == 0 ? :zero : n == 1 ? :one : n == 2 ? :two : [3, 4, 5, 6, 7, 8, 9, 10].include?(n % 100) ? :few : [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99].include?(n % 100) ? :many : :other } } } }, :az => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :be => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } }, :bg => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :bh => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :bn => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :bo => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :bs => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } }, :ca => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :cs => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n == 1 ? :one : [2, 3, 4].include?(n) ? :few : :other } } } }, :cy => { :i18n => { :plural => { :keys => [:one, :two, :many, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : n == 8 || n == 11 ? :many : :other } } } }, :da => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :de => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :dz => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :el => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :en => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :eo => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :es => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :et => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :eu => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :fa => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :fi => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :fil => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :fo => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :fr => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n.between?(0, 2) && n != 2 ? :one : :other } } } }, :fur => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :fy => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :ga => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } }, :gl => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :gu => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :guw => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :ha => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :he => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :hi => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :hr => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } }, :hu => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :id => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :is => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :it => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :iw => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :ja => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :jv => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :ka => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :km => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :kn => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :ko => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :ku => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :lb => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :ln => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :lt => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n % 10 == 1 && ![11, 12, 13, 14, 15, 16, 17, 18, 19].include?(n % 100) ? :one : [2, 3, 4, 5, 6, 7, 8, 9].include?(n % 10) && ![11, 12, 13, 14, 15, 16, 17, 18, 19].include?(n % 100) ? :few : :other } } } }, :lv => { :i18n => { :plural => { :keys => [:zero, :one, :other], :rule => lambda { |n| n == 0 ? :zero : n % 10 == 1 && n % 100 != 11 ? :one : :other } } } }, :mg => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :mk => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n % 10 == 1 ? :one : :other } } } }, :ml => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :mn => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :mo => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n == 1 ? :one : n == 0 ? :few : :other } } } }, :mr => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :ms => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :mt => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n == 1 ? :one : n == 0 || [2, 3, 4, 5, 6, 7, 8, 9, 10].include?(n % 100) ? :few : [11, 12, 13, 14, 15, 16, 17, 18, 19].include?(n % 100) ? :many : :other } } } }, :my => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :nah => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :nb => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :ne => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :nl => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :nn => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :no => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :nso => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :om => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :or => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :pa => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :pap => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :pl => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n == 1 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : (n != 1 && [0, 1].include?(n % 10)) || [5, 6, 7, 8, 9].include?(n % 10) || [12, 13, 14].include?(n % 100) ? :many : :other } } } }, :ps => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :pt => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :"pt-PT" => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :ro => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n == 1 ? :one : n == 0 ? :few : :other } } } }, :ru => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } }, :se => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } }, :sh => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } }, :sk => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n == 1 ? :one : [2, 3, 4].include?(n) ? :few : :other } } } }, :sl => { :i18n => { :plural => { :keys => [:one, :two, :few, :other], :rule => lambda { |n| n % 100 == 1 ? :one : n % 100 == 2 ? :two : [3, 4].include?(n % 100) ? :few : :other } } } }, :sma => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } }, :smi => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } }, :smj => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } }, :smn => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } }, :sms => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } }, :so => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :sq => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :sr => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } }, :sv => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :sw => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :ta => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :te => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :th => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :ti => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :tk => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :tl => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :to => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :tr => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :uk => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } }, :ur => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }, :vi => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :wa => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } }, :yo => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :zh => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } }, :zu => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } } }
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/gettext/backend_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/gettext/backend_test.rb
# encoding: utf-8 require 'test_helper' class I18nGettextBackendTest < I18n::TestCase include I18n::Gettext::Helpers class Backend < I18n::Backend::Simple include I18n::Backend::Gettext end def setup super I18n.backend = Backend.new I18n.locale = :en I18n.load_path = ["#{locales_dir}/de.po"] I18n.default_separator = '|' end def test_backend_loads_po_file I18n.backend.send(:init_translations) assert I18n.backend.send(:translations)[:de][:"Axis"] end def test_looks_up_a_translation I18n.locale = :de assert_equal 'Auto', gettext('car') end def test_uses_default_translation assert_equal 'car', gettext('car') end def test_looks_up_a_namespaced_translation I18n.locale = :de assert_equal 'Räderzahl', sgettext('Car|Wheels count') assert_equal 'Räderzahl', pgettext('Car', 'Wheels count') assert_equal 'Räderzahl!', pgettext('New car', 'Wheels count') end def test_uses_namespaced_default_translation assert_equal 'Wheels count', sgettext('Car|Wheels count') assert_equal 'Wheels count', pgettext('Car', 'Wheels count') assert_equal 'Wheels count', pgettext('New car', 'Wheels count') end def test_pluralizes_entry I18n.locale = :de assert_equal 'Achse', ngettext('Axis', 'Axis', 1) assert_equal 'Achsen', ngettext('Axis', 'Axis', 2) end def test_pluralizes_default_entry assert_equal 'Axis', ngettext('Axis', 'Axis', 1) assert_equal 'Axis', ngettext('Axis', 'Axis', 2) end def test_pluralizes_namespaced_entry I18n.locale = :de assert_equal 'Rad', nsgettext('Car|wheel', 'wheels', 1) assert_equal 'Räder', nsgettext('Car|wheel', 'wheels', 2) assert_equal 'Rad', npgettext('Car', 'wheel', 'wheels', 1) assert_equal 'Räder', npgettext('Car', 'wheel', 'wheels', 2) assert_equal 'Rad!', npgettext('New car', 'wheel', 'wheels', 1) assert_equal 'Räder!', npgettext('New car', 'wheel', 'wheels', 2) end def test_pluralizes_namespaced_default_entry assert_equal 'wheel', nsgettext('Car|wheel', 'wheels', 1) assert_equal 'wheels', nsgettext('Car|wheel', 'wheels', 2) assert_equal 'wheel', npgettext('Car', 'wheel', 'wheels', 1) assert_equal 'wheels', npgettext('Car', 'wheel', 'wheels', 2) assert_equal 'wheel', npgettext('New car', 'wheel', 'wheels', 1) assert_equal 'wheels', npgettext('New car', 'wheel', 'wheels', 2) end def test_pluralizes_namespaced_entry_with_alternative_syntax I18n.locale = :de assert_equal 'Rad', nsgettext(['Car|wheel', 'wheels'], 1) assert_equal 'Räder', nsgettext(['Car|wheel', 'wheels'], 2) assert_equal 'Rad', npgettext('Car', ['wheel', 'wheels'], 1) assert_equal 'Räder', npgettext('Car', ['wheel', 'wheels'], 2) assert_equal 'Rad!', npgettext('New car', ['wheel', 'wheels'], 1) assert_equal 'Räder!', npgettext('New car', ['wheel', 'wheels'], 2) end def test_ngettextpluralizes_entry_with_dots I18n.locale = :de assert_equal 'Auf 1 Achse.', n_("On %{count} wheel.", "On %{count} wheels.", 1) assert_equal 'Auf 2 Achsen.', n_("On %{count} wheel.", "On %{count} wheels.", 2) end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/gettext/api_test.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/test/gettext/api_test.rb
# encoding: utf-8 require 'test_helper' require 'i18n/gettext/helpers' include I18n::Gettext::Helpers class I18nGettextApiTest < I18n::TestCase def setup super I18n.locale = :en I18n.backend.store_translations :de, { 'Hi Gettext!' => 'Hallo Gettext!', 'Sentence 1. Sentence 2.' => 'Satz 1. Satz 2.', "An apple" => { :one => 'Ein Apfel', :other => '%{count} Äpfel' }, :special => { "A special apple" => { :one => 'Ein spezieller Apfel', :other => '%{count} spezielle Äpfel' } }, :foo => { :bar => 'bar-de' }, 'foo.bar' => 'Foo Bar' }, :separator => '|' end # N_ def test_N_returns_original_msg assert_equal 'foo|bar', N_('foo|bar') I18n.locale = :de assert_equal 'Hi Gettext!', N_('Hi Gettext!') end # gettext def test_gettext_uses_msg_as_default assert_equal 'Hi Gettext!', _('Hi Gettext!') end def test_gettext_uses_msg_as_key I18n.locale = :de assert_equal 'Hallo Gettext!', gettext('Hi Gettext!') assert_equal 'Hallo Gettext!', _('Hi Gettext!') end def test_gettext_uses_msg_containing_dots_as_default assert_equal 'Sentence 1. Sentence 2.', gettext('Sentence 1. Sentence 2.') assert_equal 'Sentence 1. Sentence 2.', _('Sentence 1. Sentence 2.') end def test_gettext_uses_msg_containing_dots_as_key I18n.locale = :de assert_equal 'Satz 1. Satz 2.', gettext('Sentence 1. Sentence 2.') assert_equal 'Satz 1. Satz 2.', _('Sentence 1. Sentence 2.') end # sgettext def test_sgettext_defaults_to_the_last_token_of_a_scoped_msgid assert_equal 'bar', sgettext('foo|bar') assert_equal 'bar', s_('foo|bar') end def test_sgettext_looks_up_a_scoped_translation I18n.locale = :de assert_equal 'bar-de', sgettext('foo|bar') assert_equal 'bar-de', s_('foo|bar') end def test_sgettext_ignores_dots I18n.locale = :de assert_equal 'Foo Bar', sgettext('foo.bar') assert_equal 'Foo Bar', s_('foo.bar') end # pgettext def test_pgettext_defaults_to_msgid assert_equal 'bar', pgettext('foo', 'bar') assert_equal 'bar', p_('foo', 'bar') end def test_pgettext_looks_up_a_scoped_translation I18n.locale = :de assert_equal 'bar-de', pgettext('foo', 'bar') assert_equal 'bar-de', p_('foo', 'bar') end # ngettext def test_ngettext_looks_up_msg_id_as_default_singular assert_equal 'An apple', ngettext('An apple', '%{count} apples', 1) assert_equal 'An apple', n_('An apple', '%{count} apples', 1) end def test_ngettext_looks_up_msg_id_plural_as_default_plural assert_equal '2 apples', ngettext('An apple', '%{count} apples', 2) assert_equal '2 apples', n_('An apple', '%{count} apples', 2) end def test_ngettext_looks_up_a_singular I18n.locale = :de assert_equal 'Ein Apfel', ngettext('An apple', '%{count} apples', 1) assert_equal 'Ein Apfel', n_('An apple', '%{count} apples', 1) end def test_ngettext_looks_up_a_plural I18n.locale = :de assert_equal '2 Äpfel', ngettext('An apple', '%{count} apples', 2) assert_equal '2 Äpfel', n_('An apple', '%{count} apples', 2) end def test_ngettext_looks_up_msg_id_as_default_singular_with_alternative_syntax assert_equal 'An apple', ngettext(['An apple', '%{count} apples'], 1) assert_equal 'An apple', n_(['An apple', '%{count} apples'], 1) end def test_ngettext_looks_up_msg_id_plural_as_default_plural_with_alternative_syntax assert_equal '2 apples', ngettext(['An apple', '%{count} apples'], 2) assert_equal '2 apples', n_(['An apple', '%{count} apples'], 2) end def test_ngettext_looks_up_a_singular_with_alternative_syntax I18n.locale = :de assert_equal 'Ein Apfel', ngettext(['An apple', '%{count} apples'], 1) assert_equal 'Ein Apfel', n_(['An apple', '%{count} apples'], 1) end def test_ngettext_looks_up_a_plural_with_alternative_syntax I18n.locale = :de assert_equal '2 Äpfel', ngettext(['An apple', '%{count} apples'], 2) assert_equal '2 Äpfel', n_(['An apple', '%{count} apples'], 2) end # nsgettext def test_nsgettext_looks_up_msg_id_as_default_singular assert_equal 'A special apple', nsgettext('special|A special apple', '%{count} special apples', 1) assert_equal 'A special apple', ns_('special|A special apple', '%{count} special apples', 1) end def test_nsgettext_looks_up_msg_id_plural_as_default_plural assert_equal '2 special apples', nsgettext('special|A special apple', '%{count} special apples', 2) assert_equal '2 special apples', ns_('special|A special apple', '%{count} special apples', 2) end def test_nsgettext_looks_up_a_singular I18n.locale = :de assert_equal 'Ein spezieller Apfel', nsgettext('special|A special apple', '%{count} special apples', 1) assert_equal 'Ein spezieller Apfel', ns_('special|A special apple', '%{count} special apples', 1) end def test_nsgettext_looks_up_a_plural I18n.locale = :de assert_equal '2 spezielle Äpfel', nsgettext('special|A special apple', '%{count} special apples', 2) assert_equal '2 spezielle Äpfel', ns_('special|A special apple', '%{count} special apples', 2) end def test_nsgettext_looks_up_msg_id_as_default_singular_with_alternative_syntax assert_equal 'A special apple', nsgettext(['special|A special apple', '%{count} special apples'], 1) assert_equal 'A special apple', ns_(['special|A special apple', '%{count} special apples'], 1) end def test_nsgettext_looks_up_msg_id_plural_as_default_plural_with_alternative_syntax assert_equal '2 special apples', nsgettext(['special|A special apple', '%{count} special apples'], 2) assert_equal '2 special apples', ns_(['special|A special apple', '%{count} special apples'], 2) end def test_nsgettext_looks_up_a_singular_with_alternative_syntax I18n.locale = :de assert_equal 'Ein spezieller Apfel', nsgettext(['special|A special apple', '%{count} special apples'], 1) assert_equal 'Ein spezieller Apfel', ns_(['special|A special apple', '%{count} special apples'], 1) end def test_nsgettext_looks_up_a_plural_with_alternative_syntax I18n.locale = :de assert_equal '2 spezielle Äpfel', nsgettext(['special|A special apple', '%{count} special apples'], 2) assert_equal '2 spezielle Äpfel', ns_(['special|A special apple', '%{count} special apples'], 2) end # npgettext def test_npgettext_looks_up_msg_id_as_default_singular assert_equal 'A special apple', npgettext('special', 'A special apple', '%{count} special apples', 1) assert_equal 'A special apple', np_('special', 'A special apple', '%{count} special apples', 1) end def test_npgettext_looks_up_msg_id_plural_as_default_plural assert_equal '2 special apples', npgettext('special', 'A special apple', '%{count} special apples', 2) assert_equal '2 special apples', np_('special', 'A special apple', '%{count} special apples', 2) end def test_npgettext_looks_up_a_singular I18n.locale = :de assert_equal 'Ein spezieller Apfel', npgettext('special', 'A special apple', '%{count} special apples', 1) assert_equal 'Ein spezieller Apfel', np_('special', 'A special apple', '%{count} special apples', 1) end def test_npgettext_looks_up_a_plural I18n.locale = :de assert_equal '2 spezielle Äpfel', npgettext('special', 'A special apple', '%{count} special apples', 2) assert_equal '2 spezielle Äpfel', np_('special', 'A special apple', '%{count} special apples', 2) end def test_npgettext_looks_up_msg_id_as_default_singular_with_alternative_syntax assert_equal 'A special apple', npgettext('special', ['A special apple', '%{count} special apples'], 1) assert_equal 'A special apple', np_('special', ['A special apple', '%{count} special apples'], 1) end def test_npgettext_looks_up_msg_id_plural_as_default_plural_with_alternative_syntax assert_equal '2 special apples', npgettext('special', ['A special apple', '%{count} special apples'], 2) assert_equal '2 special apples', np_('special', ['A special apple', '%{count} special apples'], 2) end def test_npgettext_looks_up_a_singular_with_alternative_syntax I18n.locale = :de assert_equal 'Ein spezieller Apfel', npgettext('special', ['A special apple', '%{count} special apples'], 1) assert_equal 'Ein spezieller Apfel', np_('special', ['A special apple', '%{count} special apples'], 1) end def test_npgettext_looks_up_a_plural_with_alternative_syntax I18n.locale = :de assert_equal '2 spezielle Äpfel', npgettext('special', ['A special apple', '%{count} special apples'], 2) assert_equal '2 spezielle Äpfel', np_('special', ['A special apple', '%{count} special apples'], 2) end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n.rb
require 'concurrent/map' require 'i18n/version' require 'i18n/exceptions' require 'i18n/interpolate/ruby' module I18n autoload :Backend, 'i18n/backend' autoload :Config, 'i18n/config' autoload :Gettext, 'i18n/gettext' autoload :Locale, 'i18n/locale' autoload :Tests, 'i18n/tests' autoload :Middleware, 'i18n/middleware' RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :fallback_in_progress, :format, :cascade, :throw, :raise, :deep_interpolation] RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/ def self.new_double_nested_cache # :nodoc: Concurrent::Map.new { |h,k| h[k] = Concurrent::Map.new } end module Base # Gets I18n configuration object. def config Thread.current[:i18n_config] ||= I18n::Config.new end # Sets I18n configuration object. def config=(value) Thread.current[:i18n_config] = value end # Write methods which delegates to the configuration object %w(locale backend default_locale available_locales default_separator exception_handler load_path enforce_available_locales).each do |method| module_eval <<-DELEGATORS, __FILE__, __LINE__ + 1 def #{method} config.#{method} end def #{method}=(value) config.#{method} = (value) end DELEGATORS end # Tells the backend to reload translations. Used in situations like the # Rails development environment. Backends can implement whatever strategy # is useful. def reload! config.clear_available_locales_set config.backend.reload! end # Translates, pluralizes and interpolates a given key using a given locale, # scope, and default, as well as interpolation values. # # *LOOKUP* # # Translation data is organized as a nested hash using the upper-level keys # as namespaces. <em>E.g.</em>, ActionView ships with the translation: # <tt>:date => {:formats => {:short => "%b %d"}}</tt>. # # Translations can be looked up at any level of this hash using the key argument # and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt> # returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>. # # Key can be either a single key or a dot-separated key (both Strings and Symbols # work). <em>E.g.</em>, the short format can be looked up using both: # I18n.t 'date.formats.short' # I18n.t :'date.formats.short' # # Scope can be either a single key, a dot-separated key or an array of keys # or dot-separated keys. Keys and scopes can be combined freely. So these # examples will all look up the same short date format: # I18n.t 'date.formats.short' # I18n.t 'formats.short', :scope => 'date' # I18n.t 'short', :scope => 'date.formats' # I18n.t 'short', :scope => %w(date formats) # # *INTERPOLATION* # # Translations can contain interpolation variables which will be replaced by # values passed to #translate as part of the options hash, with the keys matching # the interpolation variable names. # # <em>E.g.</em>, with a translation <tt>:foo => "foo %{bar}"</tt> the option # value for the key +bar+ will be interpolated into the translation: # I18n.t :foo, :bar => 'baz' # => 'foo baz' # # *PLURALIZATION* # # Translation data can contain pluralized translations. Pluralized translations # are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>. # # Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English # pluralization rules. Other algorithms can be supported by custom backends. # # This returns the singular version of a pluralized translation: # I18n.t :foo, :count => 1 # => 'Foo' # # These both return the plural version of a pluralized translation: # I18n.t :foo, :count => 0 # => 'Foos' # I18n.t :foo, :count => 2 # => 'Foos' # # The <tt>:count</tt> option can be used both for pluralization and interpolation. # <em>E.g.</em>, with the translation # <tt>:foo => ['%{count} foo', '%{count} foos']</tt>, count will # be interpolated to the pluralized translation: # I18n.t :foo, :count => 1 # => '1 foo' # # *DEFAULTS* # # This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found: # I18n.t :foo, :default => 'default' # # This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no # translation for <tt>:foo</tt> was found: # I18n.t :foo, :default => :bar # # Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> # or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found. # I18n.t :foo, :default => [:bar, 'default'] # # *BULK LOOKUP* # # This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>. # I18n.t [:foo, :bar] # # Can be used with dot-separated nested keys: # I18n.t [:'baz.foo', :'baz.bar'] # # Which is the same as using a scope option: # I18n.t [:foo, :bar], :scope => :baz # # *LAMBDAS* # # Both translations and defaults can be given as Ruby lambdas. Lambdas will be # called and passed the key and options. # # E.g. assuming the key <tt>:salutation</tt> resolves to: # lambda { |key, options| options[:gender] == 'm' ? "Mr. #{options[:name]}" : "Mrs. #{options[:name]}" } # # Then <tt>I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith". # # Note that the string returned by lambda will go through string interpolation too, # so the following lambda would give the same result: # lambda { |key, options| options[:gender] == 'm' ? "Mr. %{name}" : "Mrs. %{name}" } # # It is recommended to use/implement lambdas in an "idempotent" way. E.g. when # a cache layer is put in front of I18n.translate it will generate a cache key # from the argument values passed to #translate. Therefor your lambdas should # always return the same translations/values per unique combination of argument # values. def translate(*args) options = args.last.is_a?(Hash) ? args.pop.dup : {} key = args.shift backend = config.backend locale = options.delete(:locale) || config.locale handling = options.delete(:throw) && :throw || options.delete(:raise) && :raise # TODO deprecate :raise enforce_available_locales!(locale) result = catch(:exception) do if key.is_a?(Array) key.map { |k| backend.translate(locale, k, options) } else backend.translate(locale, key, options) end end result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result end alias :t :translate # Wrapper for <tt>translate</tt> that adds <tt>:raise => true</tt>. With # this option, if no translation is found, it will raise <tt>I18n::MissingTranslationData</tt> def translate!(key, options={}) translate(key, options.merge(:raise => true)) end alias :t! :translate! # Returns true if a translation exists for a given key, otherwise returns false. def exists?(key, locale = config.locale) raise I18n::ArgumentError if key.is_a?(String) && key.empty? config.backend.exists?(locale, key) end # Transliterates UTF-8 characters to ASCII. By default this method will # transliterate only Latin strings to an ASCII approximation: # # I18n.transliterate("Ærøskøbing") # # => "AEroskobing" # # I18n.transliterate("日本語") # # => "???" # # It's also possible to add support for per-locale transliterations. I18n # expects transliteration rules to be stored at # <tt>i18n.transliterate.rule</tt>. # # Transliteration rules can either be a Hash or a Proc. Procs must accept a # single string argument. Hash rules inherit the default transliteration # rules, while Procs do not. # # *Examples* # # Setting a Hash in <locale>.yml: # # i18n: # transliterate: # rule: # ü: "ue" # ö: "oe" # # Setting a Hash using Ruby: # # store_translations(:de, :i18n => { # :transliterate => { # :rule => { # "ü" => "ue", # "ö" => "oe" # } # } # ) # # Setting a Proc: # # translit = lambda {|string| MyTransliterator.transliterate(string) } # store_translations(:xx, :i18n => {:transliterate => {:rule => translit}) # # Transliterating strings: # # I18n.locale = :en # I18n.transliterate("Jürgen") # => "Jurgen" # I18n.locale = :de # I18n.transliterate("Jürgen") # => "Juergen" # I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen" # I18n.transliterate("Jürgen", :locale => :de) # => "Juergen" def transliterate(*args) options = args.pop.dup if args.last.is_a?(Hash) key = args.shift locale = options && options.delete(:locale) || config.locale handling = options && (options.delete(:throw) && :throw || options.delete(:raise) && :raise) replacement = options && options.delete(:replacement) enforce_available_locales!(locale) config.backend.transliterate(locale, key, replacement) rescue I18n::ArgumentError => exception handle_exception(handling, exception, locale, key, options || {}) end # Localizes certain objects, such as dates and numbers to local formatting. def localize(object, options = nil) options = options ? options.dup : {} locale = options.delete(:locale) || config.locale format = options.delete(:format) || :default enforce_available_locales!(locale) config.backend.localize(locale, object, format, options) end alias :l :localize # Executes block with given I18n.locale set. def with_locale(tmp_locale = nil) if tmp_locale current_locale = self.locale self.locale = tmp_locale end yield ensure self.locale = current_locale if tmp_locale end # Merges the given locale, key and scope into a single array of keys. # Splits keys that contain dots into multiple keys. Makes sure all # keys are Symbols. def normalize_keys(locale, key, scope, separator = nil) separator ||= I18n.default_separator keys = [] keys.concat normalize_key(locale, separator) keys.concat normalize_key(scope, separator) keys.concat normalize_key(key, separator) keys end # Returns true when the passed locale, which can be either a String or a # Symbol, is in the list of available locales. Returns false otherwise. def locale_available?(locale) I18n.config.available_locales_set.include?(locale) end # Raises an InvalidLocale exception when the passed locale is not available. def enforce_available_locales!(locale) if config.enforce_available_locales raise I18n::InvalidLocale.new(locale) if !locale_available?(locale) end end def available_locales_initialized? config.available_locales_initialized? end private # Any exceptions thrown in translate will be sent to the @@exception_handler # which can be a Symbol, a Proc or any other Object unless they're forced to # be raised or thrown (MissingTranslation). # # If exception_handler is a Symbol then it will simply be sent to I18n as # a method call. A Proc will simply be called. In any other case the # method #call will be called on the exception_handler object. # # Examples: # # I18n.exception_handler = :custom_exception_handler # this is the default # I18n.custom_exception_handler(exception, locale, key, options) # will be called like this # # I18n.exception_handler = lambda { |*args| ... } # a lambda # I18n.exception_handler.call(exception, locale, key, options) # will be called like this # # I18n.exception_handler = I18nExceptionHandler.new # an object # I18n.exception_handler.call(exception, locale, key, options) # will be called like this def handle_exception(handling, exception, locale, key, options) case handling when :raise raise exception.respond_to?(:to_exception) ? exception.to_exception : exception when :throw throw :exception, exception else case handler = options[:exception_handler] || config.exception_handler when Symbol send(handler, exception, locale, key, options) else handler.call(exception, locale, key, options) end end end @@normalized_key_cache = I18n.new_double_nested_cache def normalize_key(key, separator) @@normalized_key_cache[separator][key] ||= case key when Array key.map { |k| normalize_key(k, separator) }.flatten else keys = key.to_s.split(separator) keys.delete('') keys.map! { |k| k.to_sym } keys end end end extend Base end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/version.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/version.rb
module I18n VERSION = "0.9.5" end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/exceptions.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/exceptions.rb
require 'cgi' module I18n # Handles exceptions raised in the backend. All exceptions except for # MissingTranslationData exceptions are re-thrown. When a MissingTranslationData # was caught the handler returns an error message string containing the key/scope. # Note that the exception handler is not called when the option :throw was given. class ExceptionHandler include Module.new { def call(exception, locale, key, options) case exception when MissingTranslation exception.message when Exception raise exception else throw :exception, exception end end } end class ArgumentError < ::ArgumentError; end class InvalidLocale < ArgumentError attr_reader :locale def initialize(locale) @locale = locale super "#{locale.inspect} is not a valid locale" end end class InvalidLocaleData < ArgumentError attr_reader :filename def initialize(filename, exception_message) @filename, @exception_message = filename, exception_message super "can not load translations from #{filename}: #{exception_message}" end end class MissingTranslation < ArgumentError module Base attr_reader :locale, :key, :options def initialize(locale, key, options = {}) @key, @locale, @options = key, locale, options.dup options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) } end def keys @keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys| keys << 'no key' if keys.size < 2 end end def message "translation missing: #{keys.join('.')}" end alias :to_s :message def to_exception MissingTranslationData.new(locale, key, options) end end include Base end class MissingTranslationData < ArgumentError include MissingTranslation::Base end class InvalidPluralizationData < ArgumentError attr_reader :entry, :count, :key def initialize(entry, count, key) @entry, @count, @key = entry, count, key super "translation data #{entry.inspect} can not be used with :count => #{count}. key '#{key}' is missing." end end class MissingInterpolationArgument < ArgumentError attr_reader :key, :values, :string def initialize(key, values, string) @key, @values, @string = key, values, string super "missing interpolation argument #{key.inspect} in #{string.inspect} (#{values.inspect} given)" end end class ReservedInterpolationKey < ArgumentError attr_reader :key, :string def initialize(key, string) @key, @string = key, string super "reserved key #{key.inspect} used in #{string.inspect}" end end class UnknownFileType < ArgumentError attr_reader :type, :filename def initialize(type, filename) @type, @filename = type, filename super "can not load translations from #{filename}, the file type #{type} is not known" end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/middleware.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/middleware.rb
module I18n class Middleware def initialize(app) @app = app end def call(env) @app.call(env) ensure Thread.current[:i18n_config] = I18n::Config.new end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/gettext.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/gettext.rb
module I18n module Gettext PLURAL_SEPARATOR = "\001" CONTEXT_SEPARATOR = "\004" autoload :Helpers, 'i18n/gettext/helpers' @@plural_keys = { :en => [:one, :other] } class << self # returns an array of plural keys for the given locale or the whole hash # of locale mappings to plural keys so that we can convert from gettext's # integer-index based style # TODO move this information to the pluralization module def plural_keys(*args) args.empty? ? @@plural_keys : @@plural_keys[args.first] || @@plural_keys[:en] end def extract_scope(msgid, separator) scope = msgid.to_s.split(separator) msgid = scope.pop [scope, msgid] end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend.rb
module I18n module Backend autoload :Base, 'i18n/backend/base' autoload :InterpolationCompiler, 'i18n/backend/interpolation_compiler' autoload :Cache, 'i18n/backend/cache' autoload :Cascade, 'i18n/backend/cascade' autoload :Chain, 'i18n/backend/chain' autoload :Fallbacks, 'i18n/backend/fallbacks' autoload :Flatten, 'i18n/backend/flatten' autoload :Gettext, 'i18n/backend/gettext' autoload :KeyValue, 'i18n/backend/key_value' autoload :Memoize, 'i18n/backend/memoize' autoload :Metadata, 'i18n/backend/metadata' autoload :Pluralization, 'i18n/backend/pluralization' autoload :Simple, 'i18n/backend/simple' autoload :Transliterator, 'i18n/backend/transliterator' end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale.rb
module I18n module Locale autoload :Fallbacks, 'i18n/locale/fallbacks' autoload :Tag, 'i18n/locale/tag' end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/config.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/config.rb
require 'set' module I18n class Config # The only configuration value that is not global and scoped to thread is :locale. # It defaults to the default_locale. def locale defined?(@locale) && @locale ? @locale : default_locale end # Sets the current locale pseudo-globally, i.e. in the Thread.current hash. def locale=(locale) I18n.enforce_available_locales!(locale) @locale = locale && locale.to_sym end # Returns the current backend. Defaults to +Backend::Simple+. def backend @@backend ||= Backend::Simple.new end # Sets the current backend. Used to set a custom backend. def backend=(backend) @@backend = backend end # Returns the current default locale. Defaults to :'en' def default_locale @@default_locale ||= :en end # Sets the current default locale. Used to set a custom default locale. def default_locale=(locale) I18n.enforce_available_locales!(locale) @@default_locale = locale && locale.to_sym end # Returns an array of locales for which translations are available. # Unless you explicitely set these through I18n.available_locales= # the call will be delegated to the backend. def available_locales @@available_locales ||= nil @@available_locales || backend.available_locales end # Caches the available locales list as both strings and symbols in a Set, so # that we can have faster lookups to do the available locales enforce check. def available_locales_set #:nodoc: @@available_locales_set ||= available_locales.inject(Set.new) do |set, locale| set << locale.to_s << locale.to_sym end end # Sets the available locales. def available_locales=(locales) @@available_locales = Array(locales).map { |locale| locale.to_sym } @@available_locales = nil if @@available_locales.empty? @@available_locales_set = nil end # Returns true if the available_locales have been initialized def available_locales_initialized? ( !!defined?(@@available_locales) && !!@@available_locales ) end # Clears the available locales set so it can be recomputed again after I18n # gets reloaded. def clear_available_locales_set #:nodoc: @@available_locales_set = nil end # Returns the current default scope separator. Defaults to '.' def default_separator @@default_separator ||= '.' end # Sets the current default scope separator. def default_separator=(separator) @@default_separator = separator end # Returns the current exception handler. Defaults to an instance of # I18n::ExceptionHandler. def exception_handler @@exception_handler ||= ExceptionHandler.new end # Sets the exception handler. def exception_handler=(exception_handler) @@exception_handler = exception_handler end # Returns the current handler for situations when interpolation argument # is missing. MissingInterpolationArgument will be raised by default. def missing_interpolation_argument_handler @@missing_interpolation_argument_handler ||= lambda do |missing_key, provided_hash, string| raise MissingInterpolationArgument.new(missing_key, provided_hash, string) end end # Sets the missing interpolation argument handler. It can be any # object that responds to #call. The arguments that will be passed to #call # are the same as for MissingInterpolationArgument initializer. Use +Proc.new+ # if you don't care about arity. # # == Example: # You can supress raising an exception and return string instead: # # I18n.config.missing_interpolation_argument_handler = Proc.new do |key| # "#{key} is missing" # end def missing_interpolation_argument_handler=(exception_handler) @@missing_interpolation_argument_handler = exception_handler end # Allow clients to register paths providing translation data sources. The # backend defines acceptable sources. # # E.g. the provided SimpleBackend accepts a list of paths to translation # files which are either named *.rb and contain plain Ruby Hashes or are # named *.yml and contain YAML data. So for the SimpleBackend clients may # register translation files like this: # I18n.load_path << 'path/to/locale/en.yml' def load_path @@load_path ||= [] end # Sets the load path instance. Custom implementations are expected to # behave like a Ruby Array. def load_path=(load_path) @@load_path = load_path @@available_locales_set = nil backend.reload! end # Whether or not to verify if locales are in the list of available locales. # Defaults to true. @@enforce_available_locales = true def enforce_available_locales @@enforce_available_locales end def enforce_available_locales=(enforce_available_locales) @@enforce_available_locales = enforce_available_locales end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests.rb
module I18n module Tests autoload :Basics, 'i18n/tests/basics' autoload :Defaults, 'i18n/tests/defaults' autoload :Interpolation, 'i18n/tests/interpolation' autoload :Link, 'i18n/tests/link' autoload :Localization, 'i18n/tests/localization' autoload :Lookup, 'i18n/tests/lookup' autoload :Pluralization, 'i18n/tests/pluralization' autoload :Procs, 'i18n/tests/procs' end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/pluralization.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/pluralization.rb
# encoding: utf-8 module I18n module Tests module Pluralization test "pluralization: given 0 it returns the :zero translation if it is defined" do assert_equal 'zero', I18n.t(:default => { :zero => 'zero' }, :count => 0) end test "pluralization: given 0 it returns the :other translation if :zero is not defined" do assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 0) end test "pluralization: given 1 it returns the singular translation" do assert_equal 'bar', I18n.t(:default => { :one => 'bar' }, :count => 1) end test "pluralization: given 2 it returns the :other translation" do assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 2) end test "pluralization: given 3 it returns the :other translation" do assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 3) end test "pluralization: given nil it returns the whole entry" do assert_equal({ :one => 'bar' }, I18n.t(:default => { :one => 'bar' }, :count => nil)) end test "pluralization: given incomplete pluralization data it raises I18n::InvalidPluralizationData" do assert_raise(I18n::InvalidPluralizationData) { I18n.t(:default => { :one => 'bar' }, :count => 2) } end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/procs.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/procs.rb
# encoding: utf-8 module I18n module Tests module Procs test "lookup: given a translation is a proc it calls the proc with the key and interpolation values" do I18n.backend.store_translations(:en, :a_lambda => lambda { |*args| I18n::Tests::Procs.filter_args(*args) }) assert_equal '[:a_lambda, {:foo=>"foo"}]', I18n.t(:a_lambda, :foo => 'foo') end test "defaults: given a default is a Proc it calls it with the key and interpolation values" do proc = lambda { |*args| I18n::Tests::Procs.filter_args(*args) } assert_equal '[nil, {:foo=>"foo"}]', I18n.t(nil, :default => proc, :foo => 'foo') end test "defaults: given a default is a key that resolves to a Proc it calls it with the key and interpolation values" do the_lambda = lambda { |*args| I18n::Tests::Procs.filter_args(*args) } I18n.backend.store_translations(:en, :a_lambda => the_lambda) assert_equal '[:a_lambda, {:foo=>"foo"}]', I18n.t(nil, :default => :a_lambda, :foo => 'foo') assert_equal '[:a_lambda, {:foo=>"foo"}]', I18n.t(nil, :default => [nil, :a_lambda], :foo => 'foo') end test "interpolation: given an interpolation value is a lambda it calls it with key and values before interpolating it" do proc = lambda { |*args| I18n::Tests::Procs.filter_args(*args) } assert_match %r(\[\{:foo=>#<Proc.*>\}\]), I18n.t(nil, :default => '%{foo}', :foo => proc) end test "interpolation: given a key resolves to a Proc that returns a string then interpolation still works" do proc = lambda { |*args| "%{foo}: " + I18n::Tests::Procs.filter_args(*args) } assert_equal 'foo: [nil, {:foo=>"foo"}]', I18n.t(nil, :default => proc, :foo => 'foo') end test "pluralization: given a key resolves to a Proc that returns valid data then pluralization still works" do proc = lambda { |*args| { :zero => 'zero', :one => 'one', :other => 'other' } } assert_equal 'zero', I18n.t(:default => proc, :count => 0) assert_equal 'one', I18n.t(:default => proc, :count => 1) assert_equal 'other', I18n.t(:default => proc, :count => 2) end test "lookup: given the option :resolve => false was passed it does not resolve proc translations" do I18n.backend.store_translations(:en, :a_lambda => lambda { |*args| I18n::Tests::Procs.filter_args(*args) }) assert_equal Proc, I18n.t(:a_lambda, :resolve => false).class end test "lookup: given the option :resolve => false was passed it does not resolve proc default" do assert_equal Proc, I18n.t(nil, :default => lambda { |*args| I18n::Tests::Procs.filter_args(*args) }, :resolve => false).class end def self.filter_args(*args) args.map {|arg| arg.delete(:fallback_in_progress) if arg.is_a?(Hash) ; arg }.inspect end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/interpolation.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/interpolation.rb
# encoding: utf-8 module I18n module Tests module Interpolation # If no interpolation parameter is not given, I18n should not alter the string. # This behavior is due to three reasons: # # * Checking interpolation keys in all strings hits performance, badly; # # * This allows us to retrieve untouched values through I18n. For example # I could have a middleware that returns I18n lookup results in JSON # to be processed through Javascript. Leaving the keys untouched allows # the interpolation to happen at the javascript level; # # * Security concerns: if I allow users to translate a web site, they can # insert %{} in messages causing the I18n lookup to fail in every request. # test "interpolation: given no values it does not alter the string" do assert_equal 'Hi %{name}!', interpolate(:default => 'Hi %{name}!') end test "interpolation: given values it interpolates them into the string" do assert_equal 'Hi David!', interpolate(:default => 'Hi %{name}!', :name => 'David') end test "interpolation: given a nil value it still interpolates it into the string" do assert_equal 'Hi !', interpolate(:default => 'Hi %{name}!', :name => nil) end test "interpolation: given a lambda as a value it calls it if the string contains the key" do assert_equal 'Hi David!', interpolate(:default => 'Hi %{name}!', :name => lambda { |*args| 'David' }) end test "interpolation: given a lambda as a value it does not call it if the string does not contain the key" do assert_nothing_raised { interpolate(:default => 'Hi!', :name => lambda { |*args| raise 'fail' }) } end test "interpolation: given values but missing a key it raises I18n::MissingInterpolationArgument" do assert_raise(I18n::MissingInterpolationArgument) do interpolate(:default => '%{foo}', :bar => 'bar') end end test "interpolation: it does not raise I18n::MissingInterpolationArgument for escaped variables" do assert_nothing_raised(I18n::MissingInterpolationArgument) do assert_equal 'Barr %{foo}', interpolate(:default => '%{bar} %%{foo}', :bar => 'Barr') end end test "interpolation: it does not change the original, stored translation string" do I18n.backend.store_translations(:en, :interpolate => 'Hi %{name}!') assert_equal 'Hi David!', interpolate(:interpolate, :name => 'David') assert_equal 'Hi Yehuda!', interpolate(:interpolate, :name => 'Yehuda') end test "interpolation: given an array interpolates each element" do I18n.backend.store_translations(:en, :array_interpolate => ['Hi', 'Mr. %{name}', 'or sir %{name}']) assert_equal ['Hi', 'Mr. Bartuz', 'or sir Bartuz'], interpolate(:array_interpolate, :name => 'Bartuz') end test "interpolation: given the translation is in utf-8 it still works" do assert_equal 'Häi David!', interpolate(:default => 'Häi %{name}!', :name => 'David') end test "interpolation: given the value is in utf-8 it still works" do assert_equal 'Hi ゆきひろ!', interpolate(:default => 'Hi %{name}!', :name => 'ゆきひろ') end test "interpolation: given the translation and the value are in utf-8 it still works" do assert_equal 'こんにちは、ゆきひろさん!', interpolate(:default => 'こんにちは、%{name}さん!', :name => 'ゆきひろ') end if Object.const_defined?(:Encoding) test "interpolation: given a euc-jp translation and a utf-8 value it raises Encoding::CompatibilityError" do assert_raise(Encoding::CompatibilityError) do interpolate(:default => euc_jp('こんにちは、%{name}さん!'), :name => 'ゆきひろ') end end test "interpolation: given a utf-8 translation and a euc-jp value it raises Encoding::CompatibilityError" do assert_raise(Encoding::CompatibilityError) do interpolate(:default => 'こんにちは、%{name}さん!', :name => euc_jp('ゆきひろ')) end end test "interpolation: ASCII strings in the backend should be encoded to UTF8 if interpolation options are in UTF8" do I18n.backend.store_translations 'en', 'encoding' => ('%{who} let me go'.force_encoding("ASCII")) result = I18n.t 'encoding', :who => "måmmå miå" assert_equal Encoding::UTF_8, result.encoding end test "interpolation: UTF8 strings in the backend are still returned as UTF8 with ASCII interpolation" do I18n.backend.store_translations 'en', 'encoding' => 'måmmå miå %{what}' result = I18n.t 'encoding', :what => 'let me go'.force_encoding("ASCII") assert_equal Encoding::UTF_8, result.encoding end test "interpolation: UTF8 strings in the backend are still returned as UTF8 even with numbers interpolation" do I18n.backend.store_translations 'en', 'encoding' => '%{count} times: måmmå miå' result = I18n.t 'encoding', :count => 3 assert_equal Encoding::UTF_8, result.encoding end end test "interpolation: given a translations containing a reserved key it raises I18n::ReservedInterpolationKey" do assert_raise(I18n::ReservedInterpolationKey) { interpolate(:default => '%{default}', :foo => :bar) } assert_raise(I18n::ReservedInterpolationKey) { interpolate(:default => '%{scope}', :foo => :bar) } assert_raise(I18n::ReservedInterpolationKey) { interpolate(:default => '%{separator}', :foo => :bar) } end test "interpolation: deep interpolation for default string" do assert_equal 'Hi %{name}!', interpolate(:default => 'Hi %{name}!', :deep_interpolation => true) end test "interpolation: deep interpolation for interpolated string" do assert_equal 'Hi Ann!', interpolate(:default => 'Hi %{name}!', :name => 'Ann', :deep_interpolation => true) end test "interpolation: deep interpolation for Hash" do people = { :people => { :ann => 'Ann is %{ann}', :john => 'John is %{john}' } } interpolated_people = { :people => { :ann => 'Ann is good', :john => 'John is big' } } assert_equal interpolated_people, interpolate(:default => people, :ann => 'good', :john => 'big', :deep_interpolation => true) end test "interpolation: deep interpolation for Array" do people = { :people => ['Ann is %{ann}', 'John is %{john}'] } interpolated_people = { :people => ['Ann is good', 'John is big'] } assert_equal interpolated_people, interpolate(:default => people, :ann => 'good', :john => 'big', :deep_interpolation => true) end protected def capture(stream) begin stream = stream.to_s eval "$#{stream} = StringIO.new" yield result = eval("$#{stream}").string ensure eval("$#{stream} = #{stream.upcase}") end result end def euc_jp(string) string.encode!(Encoding::EUC_JP) end def interpolate(*args) options = args.last.is_a?(Hash) ? args.pop : {} key = args.pop I18n.backend.translate('en', key, options) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization.rb
module I18n module Tests module Localization autoload :Date, 'i18n/tests/localization/date' autoload :DateTime, 'i18n/tests/localization/date_time' autoload :Time, 'i18n/tests/localization/time' autoload :Procs, 'i18n/tests/localization/procs' def self.included(base) base.class_eval do include I18n::Tests::Localization::Date include I18n::Tests::Localization::DateTime include I18n::Tests::Localization::Procs include I18n::Tests::Localization::Time end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/link.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/link.rb
# encoding: utf-8 module I18n module Tests module Link test "linked lookup: if a key resolves to a symbol it looks up the symbol" do I18n.backend.store_translations 'en', { :link => :linked, :linked => 'linked' } assert_equal 'linked', I18n.backend.translate('en', :link) end test "linked lookup: if a key resolves to a dot-separated symbol it looks up the symbol" do I18n.backend.store_translations 'en', { :link => :"foo.linked", :foo => { :linked => 'linked' } } assert_equal('linked', I18n.backend.translate('en', :link)) end test "linked lookup: if a dot-separated key resolves to a symbol it looks up the symbol" do I18n.backend.store_translations 'en', { :foo => { :link => :linked }, :linked => 'linked' } assert_equal('linked', I18n.backend.translate('en', :'foo.link')) end test "linked lookup: if a dot-separated key resolves to a dot-separated symbol it looks up the symbol" do I18n.backend.store_translations 'en', { :foo => { :link => :"bar.linked" }, :bar => { :linked => 'linked' } } assert_equal('linked', I18n.backend.translate('en', :'foo.link')) end test "linked lookup: links always refer to the absolute key" do I18n.backend.store_translations 'en', { :foo => { :link => :linked, :linked => 'linked in foo' }, :linked => 'linked absolutely' } assert_equal 'linked absolutely', I18n.backend.translate('en', :link, :scope => :foo) end test "linked lookup: a link can resolve to a namespace in the middle of a dot-separated key" do I18n.backend.store_translations 'en', { :activemodel => { :errors => { :messages => { :blank => "can't be blank" } } }, :activerecord => { :errors => { :messages => :"activemodel.errors.messages" } } } assert_equal "can't be blank", I18n.t(:"activerecord.errors.messages.blank") assert_equal "can't be blank", I18n.t(:"activerecord.errors.messages.blank") end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/basics.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/basics.rb
module I18n module Tests module Basics def teardown I18n.available_locales = nil end test "available_locales returns the locales stored to the backend by default" do I18n.backend.store_translations('de', :foo => 'bar') I18n.backend.store_translations('en', :foo => 'foo') assert I18n.available_locales.include?(:de) assert I18n.available_locales.include?(:en) end test "available_locales can be set to something else independently from the actual locale data" do I18n.backend.store_translations('de', :foo => 'bar') I18n.backend.store_translations('en', :foo => 'foo') I18n.available_locales = :foo assert_equal [:foo], I18n.available_locales I18n.available_locales = [:foo, 'bar'] assert_equal [:foo, :bar], I18n.available_locales I18n.available_locales = nil assert I18n.available_locales.include?(:de) assert I18n.available_locales.include?(:en) end test "available_locales memoizes when set explicitely" do I18n.backend.expects(:available_locales).never I18n.available_locales = [:foo] I18n.backend.store_translations('de', :bar => 'baz') I18n.reload! assert_equal [:foo], I18n.available_locales end test "available_locales delegates to the backend when not set explicitely" do original_available_locales_value = I18n.backend.available_locales I18n.backend.expects(:available_locales).returns(original_available_locales_value).twice assert_equal I18n.backend.available_locales, I18n.available_locales end test "exists? is implemented by the backend" do I18n.backend.store_translations(:foo, :bar => 'baz') assert I18n.exists?(:bar, :foo) end test "storing a nil value as a translation removes it from the available locale data" do I18n.backend.store_translations(:en, :to_be_deleted => 'bar') assert_equal 'bar', I18n.t(:to_be_deleted, :default => 'baz') I18n.cache_store.clear if I18n.respond_to?(:cache_store) && I18n.cache_store I18n.backend.store_translations(:en, :to_be_deleted => nil) assert_equal 'baz', I18n.t(:to_be_deleted, :default => 'baz') end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/defaults.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/defaults.rb
# encoding: utf-8 module I18n module Tests module Defaults def setup super I18n.backend.store_translations(:en, :foo => { :bar => 'bar', :baz => 'baz' }) end test "defaults: given nil as a key it returns the given default" do assert_equal 'default', I18n.t(nil, :default => 'default') end test "defaults: given a symbol as a default it translates the symbol" do assert_equal 'bar', I18n.t(nil, :default => :'foo.bar') end test "defaults: given a symbol as a default and a scope it stays inside the scope when looking up the symbol" do assert_equal 'bar', I18n.t(:missing, :default => :bar, :scope => :foo) end test "defaults: given an array as a default it returns the first match" do assert_equal 'bar', I18n.t(:does_not_exist, :default => [:does_not_exist_2, :'foo.bar']) end test "defaults: given an array as a default with false it returns false" do assert_equal false, I18n.t(:does_not_exist, :default => [false]) end test "defaults: given false it returns false" do assert_equal false, I18n.t(:does_not_exist, :default => false) end test "defaults: given nil it returns nil" do assert_nil I18n.t(:does_not_exist, :default => nil) end test "defaults: given an array of missing keys it raises a MissingTranslationData exception" do assert_raise I18n::MissingTranslationData do I18n.t(:does_not_exist, :default => [:does_not_exist_2, :does_not_exist_3], :raise => true) end end test "defaults: using a custom scope separator" do # data must have been stored using the custom separator when using the ActiveRecord backend I18n.backend.store_translations(:en, { :foo => { :bar => 'bar' } }, { :separator => '|' }) assert_equal 'bar', I18n.t(nil, :default => :'foo|bar', :separator => '|') end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/lookup.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/lookup.rb
# encoding: utf-8 module I18n module Tests module Lookup def setup super I18n.backend.store_translations(:en, :foo => { :bar => 'bar', :baz => 'baz' }, :falsy => false, :truthy => true, :string => "a", :array => %w(a b c), :hash => { "a" => "b" }) end test "lookup: it returns a string" do assert_equal("a", I18n.t(:string)) end test "lookup: it returns hash" do assert_equal({ :a => "b" }, I18n.t(:hash)) end test "lookup: it returns an array" do assert_equal(%w(a b c), I18n.t(:array)) end test "lookup: it returns a native true" do assert I18n.t(:truthy) === true end test "lookup: it returns a native false" do assert I18n.t(:falsy) === false end test "lookup: given a missing key, no default and no raise option it returns an error message" do assert_equal "translation missing: en.missing", I18n.t(:missing) end test "lookup: given a missing key, no default and the raise option it raises MissingTranslationData" do assert_raise(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) } end test "lookup: does not raise an exception if no translation data is present for the given locale" do assert_nothing_raised { I18n.t(:foo, :locale => :xx) } end test "lookup: does not modify the options hash" do options = {} assert_equal "a", I18n.t(:string, options) assert_equal({}, options) assert_nothing_raised { I18n.t(:string, options.freeze) } end test "lookup: given an array of keys it translates all of them" do assert_equal %w(bar baz), I18n.t([:bar, :baz], :scope => [:foo]) end test "lookup: using a custom scope separator" do # data must have been stored using the custom separator when using the ActiveRecord backend I18n.backend.store_translations(:en, { :foo => { :bar => 'bar' } }, { :separator => '|' }) assert_equal 'bar', I18n.t('foo|bar', :separator => '|') end # In fact it probably *should* fail but Rails currently relies on using the default locale instead. # So we'll stick to this for now until we get it fixed in Rails. test "lookup: given nil as a locale it does not raise but use the default locale" do # assert_raise(I18n::InvalidLocale) { I18n.t(:bar, :locale => nil) } assert_nothing_raised { I18n.t(:bar, :locale => nil) } end test "lookup: a resulting String is not frozen" do assert !I18n.t(:string).frozen? end test "lookup: a resulting Array is not frozen" do assert !I18n.t(:array).frozen? end test "lookup: a resulting Hash is not frozen" do assert !I18n.t(:hash).frozen? end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization/procs.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization/procs.rb
# encoding: utf-8 module I18n module Tests module Localization module Procs test "localize: using day names from lambdas" do setup_time_proc_translations time = ::Time.utc(2008, 3, 1, 6, 0) assert_match(/Суббота/, I18n.l(time, :format => "%A, %d %B", :locale => :ru)) assert_match(/суббота/, I18n.l(time, :format => "%d %B (%A)", :locale => :ru)) end test "localize: using month names from lambdas" do setup_time_proc_translations time = ::Time.utc(2008, 3, 1, 6, 0) assert_match(/марта/, I18n.l(time, :format => "%d %B %Y", :locale => :ru)) assert_match(/Март /, I18n.l(time, :format => "%B %Y", :locale => :ru)) end test "localize: using abbreviated day names from lambdas" do setup_time_proc_translations time = ::Time.utc(2008, 3, 1, 6, 0) assert_match(/марта/, I18n.l(time, :format => "%d %b %Y", :locale => :ru)) assert_match(/март /, I18n.l(time, :format => "%b %Y", :locale => :ru)) end test "localize Date: given a format that resolves to a Proc it calls the Proc with the object" do setup_time_proc_translations date = ::Date.new(2008, 3, 1) assert_equal '[Sat, 01 Mar 2008, {}]', I18n.l(date, :format => :proc, :locale => :ru) end test "localize Date: given a format that resolves to a Proc it calls the Proc with the object and extra options" do setup_time_proc_translations date = ::Date.new(2008, 3, 1) assert_equal '[Sat, 01 Mar 2008, {:foo=>"foo"}]', I18n.l(date, :format => :proc, :foo => 'foo', :locale => :ru) end test "localize DateTime: given a format that resolves to a Proc it calls the Proc with the object" do setup_time_proc_translations datetime = ::DateTime.new(2008, 3, 1, 6) assert_equal '[Sat, 01 Mar 2008 06:00:00 +00:00, {}]', I18n.l(datetime, :format => :proc, :locale => :ru) end test "localize DateTime: given a format that resolves to a Proc it calls the Proc with the object and extra options" do setup_time_proc_translations datetime = ::DateTime.new(2008, 3, 1, 6) assert_equal '[Sat, 01 Mar 2008 06:00:00 +00:00, {:foo=>"foo"}]', I18n.l(datetime, :format => :proc, :foo => 'foo', :locale => :ru) end test "localize Time: given a format that resolves to a Proc it calls the Proc with the object" do setup_time_proc_translations time = ::Time.utc(2008, 3, 1, 6, 0) assert_equal I18n::Tests::Localization::Procs.inspect_args([time, {}]), I18n.l(time, :format => :proc, :locale => :ru) end test "localize Time: given a format that resolves to a Proc it calls the Proc with the object and extra options" do setup_time_proc_translations time = ::Time.utc(2008, 3, 1, 6, 0) options = { :foo => 'foo' } assert_equal I18n::Tests::Localization::Procs.inspect_args([time, options]), I18n.l(time, options.merge(:format => :proc, :locale => :ru)) end protected def self.inspect_args(args) args = args.map do |arg| case arg when ::Time, ::DateTime arg.strftime('%a, %d %b %Y %H:%M:%S %Z').sub('+0000', '+00:00') when ::Date arg.strftime('%a, %d %b %Y') when Hash arg.delete(:fallback_in_progress) arg.inspect else arg.inspect end end "[#{args.join(', ')}]" end def setup_time_proc_translations I18n.backend.store_translations :ru, { :time => { :formats => { :proc => lambda { |*args| I18n::Tests::Localization::Procs.inspect_args(args) } } }, :date => { :formats => { :proc => lambda { |*args| I18n::Tests::Localization::Procs.inspect_args(args) } }, :'day_names' => lambda { |key, options| (options[:format] =~ /^%A/) ? %w(Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота) : %w(воскресенье понедельник вторник среда четверг пятница суббота) }, :'month_names' => lambda { |key, options| (options[:format] =~ /(%d|%e)(\s*)?(%B)/) ? %w(января февраля марта апреля мая июня июля августа сентября октября ноября декабря).unshift(nil) : %w(Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь).unshift(nil) }, :'abbr_month_names' => lambda { |key, options| (options[:format] =~ /(%d|%e)(\s*)(%b)/) ? %w(янв. февр. марта апр. мая июня июля авг. сент. окт. нояб. дек.).unshift(nil) : %w(янв. февр. март апр. май июнь июль авг. сент. окт. нояб. дек.).unshift(nil) }, } } end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization/time.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization/time.rb
# encoding: utf-8 module I18n module Tests module Localization module Time def setup super setup_time_translations @time = ::Time.utc(2008, 3, 1, 6, 0) @other_time = ::Time.utc(2008, 3, 1, 18, 0) end test "localize Time: given the short format it uses it" do # TODO should be Mrz, shouldn't it? assert_equal '01. Mar 06:00', I18n.l(@time, :format => :short, :locale => :de) end test "localize Time: given the long format it uses it" do assert_equal '01. März 2008 06:00', I18n.l(@time, :format => :long, :locale => :de) end # TODO Seems to break on Windows because ENV['TZ'] is ignored. What's a better way to do this? # def test_localize_given_the_default_format_it_uses_it # assert_equal 'Sa, 01. Mar 2008 06:00:00 +0000', I18n.l(@time, :format => :default, :locale => :de) # end test "localize Time: given a day name format it returns the correct day name" do assert_equal 'Samstag', I18n.l(@time, :format => '%A', :locale => :de) end test "localize Time: given an abbreviated day name format it returns the correct abbreviated day name" do assert_equal 'Sa', I18n.l(@time, :format => '%a', :locale => :de) end test "localize Time: given a month name format it returns the correct month name" do assert_equal 'März', I18n.l(@time, :format => '%B', :locale => :de) end test "localize Time: given an abbreviated month name format it returns the correct abbreviated month name" do # TODO should be Mrz, shouldn't it? assert_equal 'Mar', I18n.l(@time, :format => '%b', :locale => :de) end test "localize Time: given a meridian indicator format it returns the correct meridian indicator" do assert_equal 'AM', I18n.l(@time, :format => '%p', :locale => :de) assert_equal 'PM', I18n.l(@other_time, :format => '%p', :locale => :de) end test "localize Time: given a meridian indicator format it returns the correct meridian indicator in upcase" do assert_equal 'am', I18n.l(@time, :format => '%P', :locale => :de) assert_equal 'pm', I18n.l(@other_time, :format => '%P', :locale => :de) end test "localize Time: given an unknown format it does not fail" do assert_nothing_raised { I18n.l(@time, :format => '%x') } end test "localize Time: given a format is missing it raises I18n::MissingTranslationData" do assert_raise(I18n::MissingTranslationData) { I18n.l(@time, :format => :missing) } end protected def setup_time_translations I18n.backend.store_translations :de, { :time => { :formats => { :default => "%a, %d. %b %Y %H:%M:%S %z", :short => "%d. %b %H:%M", :long => "%d. %B %Y %H:%M", }, :am => 'am', :pm => 'pm' } } end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization/date_time.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization/date_time.rb
# encoding: utf-8 module I18n module Tests module Localization module DateTime def setup super setup_datetime_translations @datetime = ::DateTime.new(2008, 3, 1, 6) @other_datetime = ::DateTime.new(2008, 3, 1, 18) end test "localize DateTime: given the short format it uses it" do # TODO should be Mrz, shouldn't it? assert_equal '01. Mar 06:00', I18n.l(@datetime, :format => :short, :locale => :de) end test "localize DateTime: given the long format it uses it" do assert_equal '01. März 2008 06:00', I18n.l(@datetime, :format => :long, :locale => :de) end test "localize DateTime: given the default format it uses it" do # TODO should be Mrz, shouldn't it? assert_equal 'Sa, 01. Mar 2008 06:00:00 +0000', I18n.l(@datetime, :format => :default, :locale => :de) end test "localize DateTime: given a day name format it returns the correct day name" do assert_equal 'Samstag', I18n.l(@datetime, :format => '%A', :locale => :de) end test "localize DateTime: given an abbreviated day name format it returns the correct abbreviated day name" do assert_equal 'Sa', I18n.l(@datetime, :format => '%a', :locale => :de) end test "localize DateTime: given a month name format it returns the correct month name" do assert_equal 'März', I18n.l(@datetime, :format => '%B', :locale => :de) end test "localize DateTime: given an abbreviated month name format it returns the correct abbreviated month name" do # TODO should be Mrz, shouldn't it? assert_equal 'Mar', I18n.l(@datetime, :format => '%b', :locale => :de) end test "localize DateTime: given a meridian indicator format it returns the correct meridian indicator" do assert_equal 'AM', I18n.l(@datetime, :format => '%p', :locale => :de) assert_equal 'PM', I18n.l(@other_datetime, :format => '%p', :locale => :de) end test "localize DateTime: given a meridian indicator format it returns the correct meridian indicator in downcase" do assert_equal 'am', I18n.l(@datetime, :format => '%P', :locale => :de) assert_equal 'pm', I18n.l(@other_datetime, :format => '%P', :locale => :de) end test "localize DateTime: given an unknown format it does not fail" do assert_nothing_raised { I18n.l(@datetime, :format => '%x') } end test "localize DateTime: given a format is missing it raises I18n::MissingTranslationData" do assert_raise(I18n::MissingTranslationData) { I18n.l(@datetime, :format => :missing) } end protected def setup_datetime_translations # time translations might have been set up in Tests::Api::Localization::Time I18n.backend.store_translations :de, { :time => { :formats => { :default => "%a, %d. %b %Y %H:%M:%S %z", :short => "%d. %b %H:%M", :long => "%d. %B %Y %H:%M" }, :am => 'am', :pm => 'pm' } } end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization/date.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/tests/localization/date.rb
# encoding: utf-8 module I18n module Tests module Localization module Date def setup super setup_date_translations @date = ::Date.new(2008, 3, 1) end test "localize Date: given the short format it uses it" do # TODO should be Mrz, shouldn't it? assert_equal '01. Mar', I18n.l(@date, :format => :short, :locale => :de) end test "localize Date: given the long format it uses it" do assert_equal '01. März 2008', I18n.l(@date, :format => :long, :locale => :de) end test "localize Date: given the default format it uses it" do assert_equal '01.03.2008', I18n.l(@date, :format => :default, :locale => :de) end test "localize Date: given a day name format it returns the correct day name" do assert_equal 'Samstag', I18n.l(@date, :format => '%A', :locale => :de) end test "localize Date: given an abbreviated day name format it returns the correct abbreviated day name" do assert_equal 'Sa', I18n.l(@date, :format => '%a', :locale => :de) end test "localize Date: given a month name format it returns the correct month name" do assert_equal 'März', I18n.l(@date, :format => '%B', :locale => :de) end test "localize Date: given an abbreviated month name format it returns the correct abbreviated month name" do # TODO should be Mrz, shouldn't it? assert_equal 'Mar', I18n.l(@date, :format => '%b', :locale => :de) end test "localize Date: given an unknown format it does not fail" do assert_nothing_raised { I18n.l(@date, :format => '%x') } end test "localize Date: does not modify the options hash" do options = { :format => '%b', :locale => :de } assert_equal 'Mar', I18n.l(@date, options) assert_equal({ :format => '%b', :locale => :de }, options) assert_nothing_raised { I18n.l(@date, options.freeze) } end test "localize Date: given nil with default value it returns default" do assert_equal 'default', I18n.l(nil, :default => 'default') end test "localize Date: given nil it raises I18n::ArgumentError" do assert_raise(I18n::ArgumentError) { I18n.l(nil) } end test "localize Date: given a plain Object it raises I18n::ArgumentError" do assert_raise(I18n::ArgumentError) { I18n.l(Object.new) } end test "localize Date: given a format is missing it raises I18n::MissingTranslationData" do assert_raise(I18n::MissingTranslationData) { I18n.l(@date, :format => :missing) } end test "localize Date: it does not alter the format string" do assert_equal '01. Februar 2009', I18n.l(::Date.parse('2009-02-01'), :format => :long, :locale => :de) assert_equal '01. Oktober 2009', I18n.l(::Date.parse('2009-10-01'), :format => :long, :locale => :de) end protected def setup_date_translations I18n.backend.store_translations :de, { :date => { :formats => { :default => "%d.%m.%Y", :short => "%d. %b", :long => "%d. %B %Y", }, :day_names => %w(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag), :abbr_day_names => %w(So Mo Di Mi Do Fr Sa), :month_names => %w(Januar Februar März April Mai Juni Juli August September Oktober November Dezember).unshift(nil), :abbr_month_names => %w(Jan Feb Mar Apr Mai Jun Jul Aug Sep Okt Nov Dez).unshift(nil) } } end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/interpolate/ruby.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/interpolate/ruby.rb
# heavily based on Masao Mutoh's gettext String interpolation extension # http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb module I18n INTERPOLATION_PATTERN = Regexp.union( /%%/, /%\{(\w+)\}/, # matches placeholders like "%{foo}" /%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d" ) class << self # Return String or raises MissingInterpolationArgument exception. # Missing argument's logic is handled by I18n.config.missing_interpolation_argument_handler. def interpolate(string, values) raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash) interpolate_hash(string, values) end def interpolate_hash(string, values) string.gsub(INTERPOLATION_PATTERN) do |match| if match == '%%' '%' else key = ($1 || $2 || match.tr("%{}", "")).to_sym value = if values.key?(key) values[key] else config.missing_interpolation_argument_handler.call(key, values, string) end value = value.call(values) if value.respond_to?(:call) $3 ? sprintf("%#{$3}", value) : value end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/core_ext/hash.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/core_ext/hash.rb
class Hash def slice(*keep_keys) h = {} keep_keys.each { |key| h[key] = fetch(key) if has_key?(key) } h end unless Hash.method_defined?(:slice) def except(*less_keys) slice(*keys - less_keys) end unless Hash.method_defined?(:except) def deep_symbolize_keys inject({}) { |result, (key, value)| value = value.deep_symbolize_keys if value.is_a?(Hash) result[(key.to_sym rescue key) || key] = value result } end unless Hash.method_defined?(:deep_symbolize_keys) # deep_merge_hash! by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809 MERGER = proc do |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &MERGER) : v2 end def deep_merge!(data) merge!(data, &MERGER) end unless Hash.method_defined?(:deep_merge!) end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/core_ext/string/interpolate.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/core_ext/string/interpolate.rb
# This file used to backport the Ruby 1.9 String interpolation syntax to Ruby 1.8. # # Since I18n has dropped support to Ruby 1.8, this file is not required anymore, # however, Rails 3.2 still requires it directly: # # https://github.com/rails/rails/blob/3-2-stable/activesupport/lib/active_support/core_ext/string/interpolation.rb#L2 # # So we can't just drop the file entirely, which would then break Rails users # under Ruby 1.9. This file can be removed once Rails 3.2 support is dropped.
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/core_ext/kernel/suppress_warnings.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/core_ext/kernel/suppress_warnings.rb
module Kernel def suppress_warnings original_verbosity, $VERBOSE = $VERBOSE, nil yield ensure $VERBOSE = original_verbosity end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/memoize.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/memoize.rb
# Memoize module simply memoizes the values returned by lookup using # a flat hash and can tremendously speed up the lookup process in a backend. # # To enable it you can simply include the Memoize module to your backend: # # I18n::Backend::Simple.include(I18n::Backend::Memoize) # # Notice that it's the responsibility of the backend to define whenever the # cache should be cleaned. module I18n module Backend module Memoize def available_locales @memoized_locales ||= super end def store_translations(locale, data, options = {}) reset_memoizations!(locale) super end def reload! reset_memoizations! super end protected def lookup(locale, key, scope = nil, options = {}) flat_key = I18n::Backend::Flatten.normalize_flat_keys(locale, key, scope, options[:separator]).to_sym flat_hash = memoized_lookup[locale.to_sym] flat_hash.key?(flat_key) ? flat_hash[flat_key] : (flat_hash[flat_key] = super) end def memoized_lookup @memoized_lookup ||= I18n.new_double_nested_cache end def reset_memoizations!(locale=nil) @memoized_locales = nil (locale ? memoized_lookup[locale.to_sym] : memoized_lookup).clear end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/pluralization.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/pluralization.rb
# I18n Pluralization are useful when you want your application to # customize pluralization rules. # # To enable locale specific pluralizations you can simply include the # Pluralization module to the Simple backend - or whatever other backend you # are using. # # I18n::Backend::Simple.include(I18n::Backend::Pluralization) # # You also need to make sure to provide pluralization algorithms to the # backend, i.e. include them to your I18n.load_path accordingly. module I18n module Backend module Pluralization # Overwrites the Base backend translate method so that it will check the # translation meta data space (:i18n) for a locale specific pluralization # rule and use it to pluralize the given entry. I.e. the library expects # pluralization rules to be stored at I18n.t(:'i18n.plural.rule') # # Pluralization rules are expected to respond to #call(count) and # return a pluralization key. Valid keys depend on the translation data # hash (entry) but it is generally recommended to follow CLDR's style, # i.e., return one of the keys :zero, :one, :few, :many, :other. # # The :zero key is always picked directly when count equals 0 AND the # translation data has the key :zero. This way translators are free to # either pick a special :zero translation even for languages where the # pluralizer does not return a :zero key. def pluralize(locale, entry, count) return entry unless entry.is_a?(Hash) and count pluralizer = pluralizer(locale) if pluralizer.respond_to?(:call) key = count == 0 && entry.has_key?(:zero) ? :zero : pluralizer.call(count) raise InvalidPluralizationData.new(entry, count, key) unless entry.has_key?(key) entry[key] else super end end protected def pluralizers @pluralizers ||= {} end def pluralizer(locale) pluralizers[locale] ||= I18n.t(:'i18n.plural.rule', :locale => locale, :resolve => false) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/cascade.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/cascade.rb
# The Cascade module adds the ability to do cascading lookups to backends that # are compatible to the Simple backend. # # By cascading lookups we mean that for any key that can not be found the # Cascade module strips one segment off the scope part of the key and then # tries to look up the key in that scope. # # E.g. when a lookup for the key :"foo.bar.baz" does not yield a result then # the segment :bar will be stripped off the scope part :"foo.bar" and the new # scope :foo will be used to look up the key :baz. If that does not succeed # then the remaining scope segment :foo will be omitted, too, and again the # key :baz will be looked up (now with no scope). # # To enable a cascading lookup one passes the :cascade option: # # I18n.t(:'foo.bar.baz', :cascade => true) # # This will return the first translation found for :"foo.bar.baz", :"foo.baz" # or :baz in this order. # # The cascading lookup takes precedence over resolving any given defaults. # I.e. defaults will kick in after the cascading lookups haven't succeeded. # # This behavior is useful for libraries like ActiveRecord validations where # the library wants to give users a bunch of more or less fine-grained options # of scopes for a particular key. # # Thanks to Clemens Kofler for the initial idea and implementation! See # http://github.com/clemens/i18n-cascading-backend module I18n module Backend module Cascade def lookup(locale, key, scope = [], options = {}) return super unless cascade = options[:cascade] cascade = { :step => 1 } unless cascade.is_a?(Hash) step = cascade[:step] || 1 offset = cascade[:offset] || 1 separator = options[:separator] || I18n.default_separator skip_root = cascade.has_key?(:skip_root) ? cascade[:skip_root] : true scope = I18n.normalize_keys(nil, key, scope, separator) key = (scope.slice!(-offset, offset) || []).join(separator) begin result = super return result unless result.nil? scope = scope.dup end while (!scope.empty? || !skip_root) && scope.slice!(-step, step) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/chain.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/chain.rb
module I18n module Backend # Backend that chains multiple other backends and checks each of them when # a translation needs to be looked up. This is useful when you want to use # standard translations with a Simple backend but store custom application # translations in a database or other backends. # # To use the Chain backend instantiate it and set it to the I18n module. # You can add chained backends through the initializer or backends # accessor: # # # preserves the existing Simple backend set to I18n.backend # I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend) # # The implementation assumes that all backends added to the Chain implement # a lookup method with the same API as Simple backend does. class Chain module Implementation include Base attr_accessor :backends def initialize(*backends) self.backends = backends end def reload! backends.each { |backend| backend.reload! } end def store_translations(locale, data, options = {}) backends.first.store_translations(locale, data, options) end def available_locales backends.map { |backend| backend.available_locales }.flatten.uniq end def translate(locale, key, default_options = {}) namespace = nil options = default_options.except(:default) backends.each do |backend| catch(:exception) do options = default_options if backend == backends.last translation = backend.translate(locale, key, options) if namespace_lookup?(translation, options) namespace = _deep_merge(translation, namespace || {}) elsif !translation.nil? || (options.key?(:default) && options[:default].nil?) return translation end end end return namespace if namespace throw(:exception, I18n::MissingTranslation.new(locale, key, options)) end def exists?(locale, key) backends.any? do |backend| backend.exists?(locale, key) end end def localize(locale, object, format = :default, options = {}) backends.each do |backend| catch(:exception) do result = backend.localize(locale, object, format, options) and return result end end throw(:exception, I18n::MissingTranslation.new(locale, format, options)) end protected def namespace_lookup?(result, options) result.is_a?(Hash) && !options.has_key?(:count) end private # This is approximately what gets used in ActiveSupport. # However since we are not guaranteed to run in an ActiveSupport context # it is wise to have our own copy. We underscore it # to not pollute the namespace of the including class. def _deep_merge(hash, other_hash) copy = hash.dup other_hash.each_pair do |k,v| value_from_other = hash[k] copy[k] = value_from_other.is_a?(Hash) && v.is_a?(Hash) ? _deep_merge(value_from_other, v) : v end copy end end include Implementation end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/transliterator.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/transliterator.rb
# encoding: utf-8 module I18n module Backend module Transliterator DEFAULT_REPLACEMENT_CHAR = "?" # Given a locale and a UTF-8 string, return the locale's ASCII # approximation for the string. def transliterate(locale, string, replacement = nil) @transliterators ||= {} @transliterators[locale] ||= Transliterator.get I18n.t(:'i18n.transliterate.rule', :locale => locale, :resolve => false, :default => {}) @transliterators[locale].transliterate(string, replacement) end # Get a transliterator instance. def self.get(rule = nil) if !rule || rule.kind_of?(Hash) HashTransliterator.new(rule) elsif rule.kind_of? Proc ProcTransliterator.new(rule) else raise I18n::ArgumentError, "Transliteration rule must be a proc or a hash." end end # A transliterator which accepts a Proc as its transliteration rule. class ProcTransliterator def initialize(rule) @rule = rule end def transliterate(string, replacement = nil) @rule.call(string) end end # A transliterator which accepts a Hash of characters as its translation # rule. class HashTransliterator DEFAULT_APPROXIMATIONS = { "À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"AE", "Ç"=>"C", "È"=>"E", "É"=>"E", "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I", "Î"=>"I", "Ï"=>"I", "Ð"=>"D", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O", "Õ"=>"O", "Ö"=>"O", "×"=>"x", "Ø"=>"O", "Ù"=>"U", "Ú"=>"U", "Û"=>"U", "Ü"=>"U", "Ý"=>"Y", "Þ"=>"Th", "ß"=>"ss", "à"=>"a", "á"=>"a", "â"=>"a", "ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"ae", "ç"=>"c", "è"=>"e", "é"=>"e", "ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"d", "ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o", "ö"=>"o", "ø"=>"o", "ù"=>"u", "ú"=>"u", "û"=>"u", "ü"=>"u", "ý"=>"y", "þ"=>"th", "ÿ"=>"y", "Ā"=>"A", "ā"=>"a", "Ă"=>"A", "ă"=>"a", "Ą"=>"A", "ą"=>"a", "Ć"=>"C", "ć"=>"c", "Ĉ"=>"C", "ĉ"=>"c", "Ċ"=>"C", "ċ"=>"c", "Č"=>"C", "č"=>"c", "Ď"=>"D", "ď"=>"d", "Đ"=>"D", "đ"=>"d", "Ē"=>"E", "ē"=>"e", "Ĕ"=>"E", "ĕ"=>"e", "Ė"=>"E", "ė"=>"e", "Ę"=>"E", "ę"=>"e", "Ě"=>"E", "ě"=>"e", "Ĝ"=>"G", "ĝ"=>"g", "Ğ"=>"G", "ğ"=>"g", "Ġ"=>"G", "ġ"=>"g", "Ģ"=>"G", "ģ"=>"g", "Ĥ"=>"H", "ĥ"=>"h", "Ħ"=>"H", "ħ"=>"h", "Ĩ"=>"I", "ĩ"=>"i", "Ī"=>"I", "ī"=>"i", "Ĭ"=>"I", "ĭ"=>"i", "Į"=>"I", "į"=>"i", "İ"=>"I", "ı"=>"i", "IJ"=>"IJ", "ij"=>"ij", "Ĵ"=>"J", "ĵ"=>"j", "Ķ"=>"K", "ķ"=>"k", "ĸ"=>"k", "Ĺ"=>"L", "ĺ"=>"l", "Ļ"=>"L", "ļ"=>"l", "Ľ"=>"L", "ľ"=>"l", "Ŀ"=>"L", "ŀ"=>"l", "Ł"=>"L", "ł"=>"l", "Ń"=>"N", "ń"=>"n", "Ņ"=>"N", "ņ"=>"n", "Ň"=>"N", "ň"=>"n", "ʼn"=>"'n", "Ŋ"=>"NG", "ŋ"=>"ng", "Ō"=>"O", "ō"=>"o", "Ŏ"=>"O", "ŏ"=>"o", "Ő"=>"O", "ő"=>"o", "Œ"=>"OE", "œ"=>"oe", "Ŕ"=>"R", "ŕ"=>"r", "Ŗ"=>"R", "ŗ"=>"r", "Ř"=>"R", "ř"=>"r", "Ś"=>"S", "ś"=>"s", "Ŝ"=>"S", "ŝ"=>"s", "Ş"=>"S", "ş"=>"s", "Š"=>"S", "š"=>"s", "Ţ"=>"T", "ţ"=>"t", "Ť"=>"T", "ť"=>"t", "Ŧ"=>"T", "ŧ"=>"t", "Ũ"=>"U", "ũ"=>"u", "Ū"=>"U", "ū"=>"u", "Ŭ"=>"U", "ŭ"=>"u", "Ů"=>"U", "ů"=>"u", "Ű"=>"U", "ű"=>"u", "Ų"=>"U", "ų"=>"u", "Ŵ"=>"W", "ŵ"=>"w", "Ŷ"=>"Y", "ŷ"=>"y", "Ÿ"=>"Y", "Ź"=>"Z", "ź"=>"z", "Ż"=>"Z", "ż"=>"z", "Ž"=>"Z", "ž"=>"z" }.freeze def initialize(rule = nil) @rule = rule add_default_approximations add rule if rule end def transliterate(string, replacement = nil) replacement ||= DEFAULT_REPLACEMENT_CHAR string.gsub(/[^\x00-\x7f]/u) do |char| approximations[char] || replacement end end private def approximations @approximations ||= {} end def add_default_approximations DEFAULT_APPROXIMATIONS.each do |key, value| approximations[key] = value end end # Add transliteration rules to the approximations hash. def add(hash) hash.each do |key, value| approximations[key.to_s] = value.to_s end end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/key_value.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/key_value.rb
require 'i18n/backend/base' module I18n begin require 'oj' class JSON class << self def encode(value) Oj::Rails.encode(value) end def decode(value) Oj.load(value) end end end rescue LoadError require 'active_support/json' JSON = ActiveSupport::JSON end module Backend # This is a basic backend for key value stores. It receives on # initialization the store, which should respond to three methods: # # * store#[](key) - Used to get a value # * store#[]=(key, value) - Used to set a value # * store#keys - Used to get all keys # # Since these stores only supports string, all values are converted # to JSON before being stored, allowing it to also store booleans, # hashes and arrays. However, this store does not support Procs. # # As the ActiveRecord backend, Symbols are just supported when loading # translations from the filesystem or through explicit store translations. # # Also, avoid calling I18n.available_locales since it's a somehow # expensive operation in most stores. # # == Example # # To setup I18n to use TokyoCabinet in memory is quite straightforward: # # require 'rufus/tokyo/cabinet' # gem install rufus-tokyo # I18n.backend = I18n::Backend::KeyValue.new(Rufus::Tokyo::Cabinet.new('*')) # # == Performance # # You may make this backend even faster by including the Memoize module. # However, notice that you should properly clear the cache if you change # values directly in the key-store. # # == Subtrees # # In most backends, you are allowed to retrieve part of a translation tree: # # I18n.backend.store_translations :en, :foo => { :bar => :baz } # I18n.t "foo" #=> { :bar => :baz } # # This backend supports this feature by default, but it slows down the storage # of new data considerably and makes hard to delete entries. That said, you are # allowed to disable the storage of subtrees on initialization: # # I18n::Backend::KeyValue.new(@store, false) # # This is useful if you are using a KeyValue backend chained to a Simple backend. class KeyValue module Implementation attr_accessor :store include Base, Flatten def initialize(store, subtrees=true) @store, @subtrees = store, subtrees end def store_translations(locale, data, options = {}) escape = options.fetch(:escape, true) flatten_translations(locale, data, escape, @subtrees).each do |key, value| key = "#{locale}.#{key}" case value when Hash if @subtrees && (old_value = @store[key]) old_value = JSON.decode(old_value) value = old_value.deep_symbolize_keys.deep_merge!(value) if old_value.is_a?(Hash) end when Proc raise "Key-value stores cannot handle procs" end @store[key] = JSON.encode(value) unless value.is_a?(Symbol) end end def available_locales locales = @store.keys.map { |k| k =~ /\./; $` } locales.uniq! locales.compact! locales.map! { |k| k.to_sym } locales end protected def subtrees? @subtrees end def lookup(locale, key, scope = [], options = {}) key = normalize_flat_keys(locale, key, scope, options[:separator]) value = @store["#{locale}.#{key}"] value = JSON.decode(value) if value if value.is_a?(Hash) value.deep_symbolize_keys elsif !value.nil? value elsif !@subtrees SubtreeProxy.new("#{locale}.#{key}", @store) end end def pluralize(locale, entry, count) if subtrees? super else key = pluralization_key(entry, count) entry[key] end end end class SubtreeProxy def initialize(master_key, store) @master_key = master_key @store = store @subtree = nil end def has_key?(key) @subtree && @subtree.has_key?(key) || self[key] end def [](key) unless @subtree && value = @subtree[key] value = @store["#{@master_key}.#{key}"] if value value = JSON.decode(value) (@subtree ||= {})[key] = value end end value end def is_a?(klass) Hash == klass || super end alias :kind_of? :is_a? def instance_of?(klass) Hash == klass || super end def nil? @subtree.nil? end def inspect @subtree.inspect end end include Implementation end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/base.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/base.rb
require 'yaml' require 'i18n/core_ext/hash' require 'i18n/core_ext/kernel/suppress_warnings' module I18n module Backend module Base include I18n::Backend::Transliterator # Accepts a list of paths to translation files. Loads translations from # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml # for details. def load_translations(*filenames) filenames = I18n.load_path if filenames.empty? filenames.flatten.each { |filename| load_file(filename) } end # This method receives a locale, a data hash and options for storing translations. # Should be implemented def store_translations(locale, data, options = {}) raise NotImplementedError end def translate(locale, key, options = {}) raise I18n::ArgumentError if (key.is_a?(String) || key.is_a?(Symbol)) && key.empty? raise InvalidLocale.new(locale) unless locale return nil if key.nil? && !options.key?(:default) entry = lookup(locale, key, options[:scope], options) unless key.nil? if entry.nil? && options.key?(:default) entry = default(locale, key, options[:default], options) else entry = resolve(locale, key, entry, options) end count = options[:count] if entry.nil? && (subtrees? || !count) if (options.key?(:default) && !options[:default].nil?) || !options.key?(:default) throw(:exception, I18n::MissingTranslation.new(locale, key, options)) end end entry = entry.dup if entry.is_a?(String) entry = pluralize(locale, entry, count) if count if entry.nil? && !subtrees? throw(:exception, I18n::MissingTranslation.new(locale, key, options)) end deep_interpolation = options[:deep_interpolation] values = options.except(*RESERVED_KEYS) if values entry = if deep_interpolation deep_interpolate(locale, entry, values) else interpolate(locale, entry, values) end end entry end def exists?(locale, key) lookup(locale, key) != nil end # Acts the same as +strftime+, but uses a localised version of the # format string. Takes a key from the date/time formats translations as # a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>). def localize(locale, object, format = :default, options = {}) if object.nil? && options.include?(:default) return options[:default] end raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime) if Symbol === format key = format type = object.respond_to?(:sec) ? 'time' : 'date' options = options.merge(:raise => true, :object => object, :locale => locale) format = I18n.t(:"#{type}.formats.#{key}", options) end format = translate_localization_format(locale, object, format, options) object.strftime(format) end # Returns an array of locales for which translations are available # ignoring the reserved translation meta data key :i18n. def available_locales raise NotImplementedError end def reload! end protected # The method which actually looks up for the translation in the store. def lookup(locale, key, scope = [], options = {}) raise NotImplementedError end def subtrees? true end # Evaluates defaults. # If given subject is an Array, it walks the array and returns the # first translation that can be resolved. Otherwise it tries to resolve # the translation directly. def default(locale, object, subject, options = {}) options = options.dup.reject { |key, value| key == :default } case subject when Array subject.each do |item| result = resolve(locale, object, item, options) return result unless result.nil? end and nil else resolve(locale, object, subject, options) end end # Resolves a translation. # If the given subject is a Symbol, it will be translated with the # given options. If it is a Proc then it will be evaluated. All other # subjects will be returned directly. def resolve(locale, object, subject, options = {}) return subject if options[:resolve] == false result = catch(:exception) do case subject when Symbol I18n.translate(subject, options.merge(:locale => locale, :throw => true)) when Proc date_or_time = options.delete(:object) || object resolve(locale, object, subject.call(date_or_time, options)) else subject end end result unless result.is_a?(MissingTranslation) end # Picks a translation from a pluralized mnemonic subkey according to English # pluralization rules : # - It will pick the :one subkey if count is equal to 1. # - It will pick the :other subkey otherwise. # - It will pick the :zero subkey in the special case where count is # equal to 0 and there is a :zero subkey present. This behaviour is # not standard with regards to the CLDR pluralization rules. # Other backends can implement more flexible or complex pluralization rules. def pluralize(locale, entry, count) return entry unless entry.is_a?(Hash) && count key = pluralization_key(entry, count) raise InvalidPluralizationData.new(entry, count, key) unless entry.has_key?(key) entry[key] end # Interpolates values into a given subject. # # if the given subject is a string then: # method interpolates "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X' # # => "file test.txt opened by %{user}" # # if the given subject is an array then: # each element of the array is recursively interpolated (until it finds a string) # method interpolates ["yes, %{user}", ["maybe no, %{user}, "no, %{user}"]], :user => "bartuz" # # => "["yes, bartuz",["maybe no, bartuz", "no, bartuz"]]" def interpolate(locale, subject, values = {}) return subject if values.empty? case subject when ::String then I18n.interpolate(subject, values) when ::Array then subject.map { |element| interpolate(locale, element, values) } else subject end end # Deep interpolation # # deep_interpolate { people: { ann: "Ann is %{ann}", john: "John is %{john}" } }, # ann: 'good', john: 'big' # #=> { people: { ann: "Ann is good", john: "John is big" } } def deep_interpolate(locale, data, values = {}) return data if values.empty? case data when ::String I18n.interpolate(data, values) when ::Hash data.each_with_object({}) do |(k, v), result| result[k] = deep_interpolate(locale, v, values) end when ::Array data.map do |v| deep_interpolate(locale, v, values) end else data end end # Loads a single translations file by delegating to #load_rb or # #load_yml depending on the file extension and directly merges the # data to the existing translations. Raises I18n::UnknownFileType # for all other file extensions. def load_file(filename) type = File.extname(filename).tr('.', '').downcase raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true) data = send(:"load_#{type}", filename) unless data.is_a?(Hash) raise InvalidLocaleData.new(filename, 'expects it to return a hash, but does not') end data.each { |locale, d| store_translations(locale, d || {}) } end # Loads a plain Ruby translations file. eval'ing the file must yield # a Hash containing translation data with locales as toplevel keys. def load_rb(filename) eval(IO.read(filename), binding, filename) end # Loads a YAML translations file. The data must have locales as # toplevel keys. def load_yml(filename) begin YAML.load_file(filename) rescue TypeError, ScriptError, StandardError => e raise InvalidLocaleData.new(filename, e.inspect) end end def translate_localization_format(locale, object, format, options) format.to_s.gsub(/%[aAbBpP]/) do |match| case match when '%a' then I18n.t(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday] when '%A' then I18n.t(:"date.day_names", :locale => locale, :format => format)[object.wday] when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon] when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon] when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).upcase if object.respond_to? :hour when '%P' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).downcase if object.respond_to? :hour end end end def pluralization_key(entry, count) key = :zero if count == 0 && entry.has_key?(:zero) key ||= count == 1 ? :one : :other end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/gettext.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/gettext.rb
require 'i18n/gettext' require 'i18n/gettext/po_parser' module I18n module Backend # Experimental support for using Gettext po files to store translations. # # To use this you can simply include the module to the Simple backend - or # whatever other backend you are using. # # I18n::Backend::Simple.include(I18n::Backend::Gettext) # # Now you should be able to include your Gettext translation (*.po) files to # the +I18n.load_path+ so they're loaded to the backend and you can use them as # usual: # # I18n.load_path += Dir["path/to/locales/*.po"] # # Following the Gettext convention this implementation expects that your # translation files are named by their locales. E.g. the file en.po would # contain the translations for the English locale. # # To translate text <b>you must use</b> one of the translate methods provided by # I18n::Gettext::Helpers. # # include I18n::Gettext::Helpers # puts _("some string") # # Without it strings containing periods (".") will not be translated. module Gettext class PoData < Hash def set_comment(msgid_or_sym, comment) # ignore end end protected def load_po(filename) locale = ::File.basename(filename, '.po').to_sym data = normalize(locale, parse(filename)) { locale => data } end def parse(filename) GetText::PoParser.new.parse(::File.read(filename), PoData.new) end def normalize(locale, data) data.inject({}) do |result, (key, value)| unless key.nil? || key.empty? key = key.gsub(I18n::Gettext::CONTEXT_SEPARATOR, '|') key, value = normalize_pluralization(locale, key, value) if key.index("\000") parts = key.split('|').reverse normalized = parts.inject({}) do |_normalized, part| { part => _normalized.empty? ? value : _normalized } end result.deep_merge!(normalized) end result end end def normalize_pluralization(locale, key, value) # FIXME po_parser includes \000 chars that can not be turned into Symbols key = key.gsub("\000", I18n::Gettext::PLURAL_SEPARATOR).split(I18n::Gettext::PLURAL_SEPARATOR).first keys = I18n::Gettext.plural_keys(locale) values = value.split("\000") raise "invalid number of plurals: #{values.size}, keys: #{keys.inspect} on #{locale} locale for msgid #{key.inspect} with values #{values.inspect}" if values.size != keys.size result = {} values.each_with_index { |_value, ix| result[keys[ix]] = _value } [key, result] end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/interpolation_compiler.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/interpolation_compiler.rb
# The InterpolationCompiler module contains optimizations that can tremendously # speed up the interpolation process on the Simple backend. # # It works by defining a pre-compiled method on stored translation Strings that # already bring all the knowledge about contained interpolation variables etc. # so that the actual recurring interpolation will be very fast. # # To enable pre-compiled interpolations you can simply include the # InterpolationCompiler module to the Simple backend: # # I18n::Backend::Simple.include(I18n::Backend::InterpolationCompiler) # # Note that InterpolationCompiler does not yield meaningful results and consequently # should not be used with Ruby 1.9 (YARV) but improves performance everywhere else # (jRuby, Rubinius). module I18n module Backend module InterpolationCompiler module Compiler extend self TOKENIZER = /(%%\{[^\}]+\}|%\{[^\}]+\})/ INTERPOLATION_SYNTAX_PATTERN = /(%)?(%\{([^\}]+)\})/ def compile_if_an_interpolation(string) if interpolated_str?(string) string.instance_eval <<-RUBY_EVAL, __FILE__, __LINE__ def i18n_interpolate(v = {}) "#{compiled_interpolation_body(string)}" end RUBY_EVAL end string end def interpolated_str?(str) str.kind_of?(::String) && str =~ INTERPOLATION_SYNTAX_PATTERN end protected # tokenize("foo %{bar} baz %%{buz}") # => ["foo ", "%{bar}", " baz ", "%%{buz}"] def tokenize(str) str.split(TOKENIZER) end def compiled_interpolation_body(str) tokenize(str).map do |token| (matchdata = token.match(INTERPOLATION_SYNTAX_PATTERN)) ? handle_interpolation_token(token, matchdata) : escape_plain_str(token) end.join end def handle_interpolation_token(interpolation, matchdata) escaped, pattern, key = matchdata.values_at(1, 2, 3) escaped ? pattern : compile_interpolation_token(key.to_sym) end def compile_interpolation_token(key) "\#{#{interpolate_or_raise_missing(key)}}" end def interpolate_or_raise_missing(key) escaped_key = escape_key_sym(key) RESERVED_KEYS.include?(key) ? reserved_key(escaped_key) : interpolate_key(escaped_key) end def interpolate_key(key) [direct_key(key), nil_key(key), missing_key(key)].join('||') end def direct_key(key) "((t = v[#{key}]) && t.respond_to?(:call) ? t.call : t)" end def nil_key(key) "(v.has_key?(#{key}) && '')" end def missing_key(key) "I18n.config.missing_interpolation_argument_handler.call(#{key}, v, self)" end def reserved_key(key) "raise(ReservedInterpolationKey.new(#{key}, self))" end def escape_plain_str(str) str.gsub(/"|\\|#/) {|x| "\\#{x}"} end def escape_key_sym(key) # rely on Ruby to do all the hard work :) key.to_sym.inspect end end def interpolate(locale, string, values) if string.respond_to?(:i18n_interpolate) string.i18n_interpolate(values) elsif values super else string end end def store_translations(locale, data, options = {}) compile_all_strings_in(data) super end protected def compile_all_strings_in(data) data.each_value do |value| Compiler.compile_if_an_interpolation(value) compile_all_strings_in(value) if value.kind_of?(Hash) end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/simple.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/simple.rb
module I18n module Backend # A simple backend that reads translations from YAML files and stores them in # an in-memory hash. Relies on the Base backend. # # The implementation is provided by a Implementation module allowing to easily # extend Simple backend's behavior by including modules. E.g.: # # module I18n::Backend::Pluralization # def pluralize(*args) # # extended pluralization logic # super # end # end # # I18n::Backend::Simple.include(I18n::Backend::Pluralization) class Simple (class << self; self; end).class_eval { public :include } module Implementation include Base def initialized? @initialized ||= false end # Stores translations for the given locale in memory. # This uses a deep merge for the translations hash, so existing # translations will be overwritten by new ones only at the deepest # level of the hash. def store_translations(locale, data, options = {}) if I18n.enforce_available_locales && I18n.available_locales_initialized? && !I18n.available_locales.include?(locale.to_sym) && !I18n.available_locales.include?(locale.to_s) return data end locale = locale.to_sym translations[locale] ||= {} data = data.deep_symbolize_keys translations[locale].deep_merge!(data) end # Get available locales from the translations hash def available_locales init_translations unless initialized? translations.inject([]) do |locales, (locale, data)| locales << locale unless data.size <= 1 && (data.empty? || data.has_key?(:i18n)) locales end end # Clean up translations hash and set initialized to false on reload! def reload! @initialized = false @translations = nil super end protected def init_translations load_translations @initialized = true end def translations @translations ||= {} end # Looks up a translation from the translations hash. Returns nil if # either key is nil, or locale, scope or key do not exist as a key in the # nested translations hash. Splits keys or scopes containing dots # into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as # <tt>%w(currency format)</tt>. def lookup(locale, key, scope = [], options = {}) init_translations unless initialized? keys = I18n.normalize_keys(locale, key, scope, options[:separator]) keys.inject(translations) do |result, _key| _key = _key.to_sym return nil unless result.is_a?(Hash) && result.has_key?(_key) result = result[_key] result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol) result end end end include Implementation end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/fallbacks.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/fallbacks.rb
# I18n locale fallbacks are useful when you want your application to use # translations from other locales when translations for the current locale are # missing. E.g. you might want to use :en translations when translations in # your applications main locale :de are missing. # # To enable locale fallbacks you can simply include the Fallbacks module to # the Simple backend - or whatever other backend you are using: # # I18n::Backend::Simple.include(I18n::Backend::Fallbacks) module I18n @@fallbacks = nil class << self # Returns the current fallbacks implementation. Defaults to +I18n::Locale::Fallbacks+. def fallbacks @@fallbacks ||= I18n::Locale::Fallbacks.new end # Sets the current fallbacks implementation. Use this to set a different fallbacks implementation. def fallbacks=(fallbacks) @@fallbacks = fallbacks end end module Backend module Fallbacks # Overwrites the Base backend translate method so that it will try each # locale given by I18n.fallbacks for the given locale. E.g. for the # locale :"de-DE" it might try the locales :"de-DE", :de and :en # (depends on the fallbacks implementation) until it finds a result with # the given options. If it does not find any result for any of the # locales it will then throw MissingTranslation as usual. # # The default option takes precedence over fallback locales only when # it's a Symbol. When the default contains a String, Proc or Hash # it is evaluated last after all the fallback locales have been tried. def translate(locale, key, options = {}) return super unless options.fetch(:fallback, true) return super if options[:fallback_in_progress] default = extract_non_symbol_default!(options) if options[:default] begin options[:fallback_in_progress] = true I18n.fallbacks[locale].each do |fallback| begin catch(:exception) do result = super(fallback, key, options) return result unless result.nil? end rescue I18n::InvalidLocale # we do nothing when the locale is invalid, as this is a fallback anyways. end end ensure options.delete(:fallback_in_progress) end return if options.key?(:default) && options[:default].nil? return super(locale, nil, options.merge(:default => default)) if default throw(:exception, I18n::MissingTranslation.new(locale, key, options)) end def extract_non_symbol_default!(options) defaults = [options[:default]].flatten first_non_symbol_default = defaults.detect{|default| !default.is_a?(Symbol)} if first_non_symbol_default options[:default] = defaults[0, defaults.index(first_non_symbol_default)] end return first_non_symbol_default end def exists?(locale, key) I18n.fallbacks[locale].each do |fallback| begin return true if super(fallback, key) rescue I18n::InvalidLocale # we do nothing when the locale is invalid, as this is a fallback anyways. end end false end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/cache.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/cache.rb
# This module allows you to easily cache all responses from the backend - thus # speeding up the I18n aspects of your application quite a bit. # # To enable caching you can simply include the Cache module to the Simple # backend - or whatever other backend you are using: # # I18n::Backend::Simple.send(:include, I18n::Backend::Cache) # # You will also need to set a cache store implementation that you want to use: # # I18n.cache_store = ActiveSupport::Cache.lookup_store(:memory_store) # # You can use any cache implementation you want that provides the same API as # ActiveSupport::Cache (only the methods #fetch and #write are being used). # # The cache_key implementation by default assumes you pass values that return # a valid key from #hash (see # http://www.ruby-doc.org/core/classes/Object.html#M000337). However, you can # configure your own digest method via which responds to #hexdigest (see # http://ruby-doc.org/stdlib/libdoc/digest/rdoc/index.html): # # I18n.cache_key_digest = Digest::MD5.new # # If you use a lambda as a default value in your translation like this: # # I18n.t(:"date.order", :default => lambda {[:month, :day, :year]}) # # Then you will always have a cache miss, because each time this method # is called the lambda will have a different hash value. If you know # the result of the lambda is a constant as in the example above, then # to cache this you can make the lambda a constant, like this: # # DEFAULT_DATE_ORDER = lambda {[:month, :day, :year]} # ... # I18n.t(:"date.order", :default => DEFAULT_DATE_ORDER) # # If the lambda may result in different values for each call then consider # also using the Memoize backend. # module I18n class << self @@cache_store = nil @@cache_namespace = nil @@cache_key_digest = nil def cache_store @@cache_store end def cache_store=(store) @@cache_store = store end def cache_namespace @@cache_namespace end def cache_namespace=(namespace) @@cache_namespace = namespace end def cache_key_digest @@cache_key_digest end def cache_key_digest=(key_digest) @@cache_key_digest = key_digest end def perform_caching? !cache_store.nil? end end module Backend # TODO Should the cache be cleared if new translations are stored? module Cache def translate(locale, key, options = {}) I18n.perform_caching? ? fetch(cache_key(locale, key, options)) { super } : super end protected def fetch(cache_key, &block) result = _fetch(cache_key, &block) throw(:exception, result) if result.is_a?(MissingTranslation) result = result.dup if result.frozen? rescue result result end def _fetch(cache_key, &block) result = I18n.cache_store.read(cache_key) return result unless result.nil? result = catch(:exception, &block) I18n.cache_store.write(cache_key, result) unless result.is_a?(Proc) result end def cache_key(locale, key, options) # This assumes that only simple, native Ruby values are passed to I18n.translate. "i18n/#{I18n.cache_namespace}/#{locale}/#{digest_item(key)}/#{USE_INSPECT_HASH ? digest_item(options.inspect) : digest_item(options)}" end private # In Ruby < 1.9 the following is true: { :foo => 1, :bar => 2 }.hash == { :foo => 2, :bar => 1 }.hash # Therefore we must use the hash of the inspect string instead to avoid cache key colisions. USE_INSPECT_HASH = RUBY_VERSION <= "1.9" def digest_item(key) I18n.cache_key_digest ? I18n.cache_key_digest.hexdigest(key.to_s) : key.hash end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/metadata.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/metadata.rb
# I18n translation metadata is useful when you want to access information # about how a translation was looked up, pluralized or interpolated in # your application. # # msg = I18n.t(:message, :default => 'Hi!', :scope => :foo) # msg.translation_metadata # # => { :key => :message, :scope => :foo, :default => 'Hi!' } # # If a :count option was passed to #translate it will be set to the metadata. # Likewise, if any interpolation variables were passed they will also be set. # # To enable translation metadata you can simply include the Metadata module # into the Simple backend class - or whatever other backend you are using: # # I18n::Backend::Simple.include(I18n::Backend::Metadata) # module I18n module Backend module Metadata class << self def included(base) Object.class_eval do def translation_metadata unless self.frozen? @translation_metadata ||= {} else {} end end def translation_metadata=(translation_metadata) @translation_metadata = translation_metadata unless self.frozen? end end unless Object.method_defined?(:translation_metadata) end end def translate(locale, key, options = {}) metadata = { :locale => locale, :key => key, :scope => options[:scope], :default => options[:default], :separator => options[:separator], :values => options.reject { |name, value| RESERVED_KEYS.include?(name) } } with_metadata(metadata) { super } end def interpolate(locale, entry, values = {}) metadata = entry.translation_metadata.merge(:original => entry) with_metadata(metadata) { super } end def pluralize(locale, entry, count) with_metadata(:count => count) { super } end protected def with_metadata(metadata, &block) result = yield result.translation_metadata = result.translation_metadata.merge(metadata) if result result end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/flatten.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/backend/flatten.rb
module I18n module Backend # This module contains several helpers to assist flattening translations. # You may want to flatten translations for: # # 1) speed up lookups, as in the Memoize backend; # 2) In case you want to store translations in a data store, as in ActiveRecord backend; # # You can check both backends above for some examples. # This module also keeps all links in a hash so they can be properly resolved when flattened. module Flatten SEPARATOR_ESCAPE_CHAR = "\001" FLATTEN_SEPARATOR = "." # normalize_keys the flatten way. This method is significantly faster # and creates way less objects than the one at I18n.normalize_keys. # It also handles escaping the translation keys. def self.normalize_flat_keys(locale, key, scope, separator) keys = [scope, key].flatten.compact separator ||= I18n.default_separator if separator != FLATTEN_SEPARATOR keys.map! do |k| k.to_s.tr("#{FLATTEN_SEPARATOR}#{separator}", "#{SEPARATOR_ESCAPE_CHAR}#{FLATTEN_SEPARATOR}") end end keys.join(".") end # Receives a string and escape the default separator. def self.escape_default_separator(key) #:nodoc: key.to_s.tr(FLATTEN_SEPARATOR, SEPARATOR_ESCAPE_CHAR) end # Shortcut to I18n::Backend::Flatten.normalize_flat_keys # and then resolve_links. def normalize_flat_keys(locale, key, scope, separator) key = I18n::Backend::Flatten.normalize_flat_keys(locale, key, scope, separator) resolve_link(locale, key) end # Store flattened links. def links @links ||= I18n.new_double_nested_cache end # Flatten keys for nested Hashes by chaining up keys: # # >> { "a" => { "b" => { "c" => "d", "e" => "f" }, "g" => "h" }, "i" => "j"}.wind # => { "a.b.c" => "d", "a.b.e" => "f", "a.g" => "h", "i" => "j" } # def flatten_keys(hash, escape, prev_key=nil, &block) hash.each_pair do |key, value| key = escape_default_separator(key) if escape curr_key = [prev_key, key].compact.join(FLATTEN_SEPARATOR).to_sym yield curr_key, value flatten_keys(value, escape, curr_key, &block) if value.is_a?(Hash) end end # Receives a hash of translations (where the key is a locale and # the value is another hash) and return a hash with all # translations flattened. # # Nested hashes are included in the flattened hash just if subtree # is true and Symbols are automatically stored as links. def flatten_translations(locale, data, escape, subtree) hash = {} flatten_keys(data, escape) do |key, value| if value.is_a?(Hash) hash[key] = value if subtree else store_link(locale, key, value) if value.is_a?(Symbol) hash[key] = value end end hash end protected def store_link(locale, key, link) links[locale.to_sym][key.to_s] = link.to_s end def resolve_link(locale, key) key, locale = key.to_s, locale.to_sym links = self.links[locale] if links.key?(key) links[key] elsif link = find_link(locale, key) store_link(locale, key, key.gsub(*link)) else key end end def find_link(locale, key) #:nodoc: links[locale].each_pair do |from, to| return [from, to] if key[0, from.length] == from end && nil end def escape_default_separator(key) #:nodoc: I18n::Backend::Flatten.escape_default_separator(key) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/tag.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/tag.rb
# encoding: utf-8 module I18n module Locale module Tag autoload :Parents, 'i18n/locale/tag/parents' autoload :Rfc4646, 'i18n/locale/tag/rfc4646' autoload :Simple, 'i18n/locale/tag/simple' class << self # Returns the current locale tag implementation. Defaults to +I18n::Locale::Tag::Simple+. def implementation @@implementation ||= Simple end # Sets the current locale tag implementation. Use this to set a different locale tag implementation. def implementation=(implementation) @@implementation = implementation end # Factory method for locale tags. Delegates to the current locale tag implementation. def tag(tag) implementation.tag(tag) end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/fallbacks.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/fallbacks.rb
# Locale Fallbacks # # Extends the I18n module to hold a fallbacks instance which is set to an # instance of I18n::Locale::Fallbacks by default but can be swapped with a # different implementation. # # Locale fallbacks will compute a number of fallback locales for a given locale. # For example: # # <pre><code> # I18n.fallbacks[:"es-MX"] # => [:"es-MX", :es, :en] </code></pre> # # Locale fallbacks always fall back to # # * all parent locales of a given locale (e.g. :es for :"es-MX") first, # * the current default locales and all of their parents second # # The default locales are set to [I18n.default_locale] by default but can be # set to something else. # # One can additionally add any number of additional fallback locales manually. # These will be added before the default locales to the fallback chain. For # example: # # # using the default locale as default fallback locale # # I18n.default_locale = :"en-US" # I18n.fallbacks = I18n::Locale::Fallbacks.new(:"de-AT" => :"de-DE") # I18n.fallbacks[:"de-AT"] # => [:"de-AT", :"de-DE", :de, :"en-US", :en] # # # using a custom locale as default fallback locale # # I18n.fallbacks = I18n::Locale::Fallbacks.new(:"en-GB", :"de-AT" => :de, :"de-CH" => :de) # I18n.fallbacks[:"de-AT"] # => [:"de-AT", :de, :"en-GB", :en] # I18n.fallbacks[:"de-CH"] # => [:"de-CH", :de, :"en-GB", :en] # # # mapping fallbacks to an existing instance # # # people speaking Catalan also speak Spanish as spoken in Spain # fallbacks = I18n.fallbacks # fallbacks.map(:ca => :"es-ES") # fallbacks[:ca] # => [:ca, :"es-ES", :es, :"en-US", :en] # # # people speaking Arabian as spoken in Palestine also speak Hebrew as spoken in Israel # fallbacks.map(:"ar-PS" => :"he-IL") # fallbacks[:"ar-PS"] # => [:"ar-PS", :ar, :"he-IL", :he, :"en-US", :en] # fallbacks[:"ar-EG"] # => [:"ar-EG", :ar, :"en-US", :en] # # # people speaking Sami as spoken in Finnland also speak Swedish and Finnish as spoken in Finnland # fallbacks.map(:sms => [:"se-FI", :"fi-FI"]) # fallbacks[:sms] # => [:sms, :"se-FI", :se, :"fi-FI", :fi, :"en-US", :en] module I18n module Locale class Fallbacks < Hash def initialize(*mappings) @map = {} map(mappings.pop) if mappings.last.is_a?(Hash) self.defaults = mappings.empty? ? [I18n.default_locale.to_sym] : mappings end def defaults=(defaults) @defaults = defaults.map { |default| compute(default, false) }.flatten end attr_reader :defaults def [](locale) raise InvalidLocale.new(locale) if locale.nil? locale = locale.to_sym super || store(locale, compute(locale)) end def map(mappings) mappings.each do |from, to| from, to = from.to_sym, Array(to) to.each do |_to| @map[from] ||= [] @map[from] << _to.to_sym end end end protected def compute(tags, include_defaults = true, exclude = []) result = Array(tags).collect do |tag| tags = I18n::Locale::Tag.tag(tag).self_and_parents.map! { |t| t.to_sym } - exclude tags.each { |_tag| tags += compute(@map[_tag], false, exclude + tags) if @map[_tag] } tags end.flatten result.push(*defaults) if include_defaults result.uniq.compact end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/tag/parents.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/tag/parents.rb
module I18n module Locale module Tag module Parents def parent @parent ||= begin segs = to_a.compact segs.length > 1 ? self.class.tag(*segs[0..(segs.length-2)].join('-')) : nil end end def self_and_parents @self_and_parents ||= [self] + parents end def parents @parents ||= ([parent] + (parent ? parent.parents : [])).compact end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/tag/simple.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/tag/simple.rb
# Simple Locale tag implementation that computes subtags by simply splitting # the locale tag at '-' occurences. module I18n module Locale module Tag class Simple class << self def tag(tag) new(tag) end end include Parents attr_reader :tag def initialize(*tag) @tag = tag.join('-').to_sym end def subtags @subtags = tag.to_s.split('-').map { |subtag| subtag.to_s } end def to_sym tag end def to_s tag.to_s end def to_a subtags end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/tag/rfc4646.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/locale/tag/rfc4646.rb
# RFC 4646/47 compliant Locale tag implementation that parses locale tags to # subtags such as language, script, region, variant etc. # # For more information see by http://en.wikipedia.org/wiki/IETF_language_tag # # Rfc4646::Parser does not implement grandfathered tags. module I18n module Locale module Tag RFC4646_SUBTAGS = [ :language, :script, :region, :variant, :extension, :privateuse, :grandfathered ] RFC4646_FORMATS = { :language => :downcase, :script => :capitalize, :region => :upcase, :variant => :downcase } class Rfc4646 < Struct.new(*RFC4646_SUBTAGS) class << self # Parses the given tag and returns a Tag instance if it is valid. # Returns false if the given tag is not valid according to RFC 4646. def tag(tag) matches = parser.match(tag) new(*matches) if matches end def parser @@parser ||= Rfc4646::Parser end def parser=(parser) @@parser = parser end end include Parents RFC4646_FORMATS.each do |name, format| define_method(name) { self[name].send(format) unless self[name].nil? } end def to_sym to_s.to_sym end def to_s @tag ||= to_a.compact.join("-") end def to_a members.collect { |attr| self.send(attr) } end module Parser PATTERN = %r{\A(?: ([a-z]{2,3}(?:(?:-[a-z]{3}){0,3})?|[a-z]{4}|[a-z]{5,8}) # language (?:-([a-z]{4}))? # script (?:-([a-z]{2}|\d{3}))? # region (?:-([0-9a-z]{5,8}|\d[0-9a-z]{3}))* # variant (?:-([0-9a-wyz](?:-[0-9a-z]{2,8})+))* # extension (?:-(x(?:-[0-9a-z]{1,8})+))?| # privateuse subtag (x(?:-[0-9a-z]{1,8})+)| # privateuse tag /* ([a-z]{1,3}(?:-[0-9a-z]{2,8}){1,2}) */ # grandfathered )\z}xi class << self def match(tag) c = PATTERN.match(tag.to_s).captures c[0..4] << (c[5].nil? ? c[6] : c[5]) << c[7] # TODO c[7] is grandfathered, throw a NotImplemented exception here? rescue false end end end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/gettext/helpers.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/gettext/helpers.rb
require 'i18n/gettext' module I18n module Gettext # Implements classical Gettext style accessors. To use this include the # module to the global namespace or wherever you want to use it. # # include I18n::Gettext::Helpers module Helpers # Makes dynamic translation messages readable for the gettext parser. # <tt>_(fruit)</tt> cannot be understood by the gettext parser. To help the parser find all your translations, # you can add <tt>fruit = N_("Apple")</tt> which does not translate, but tells the parser: "Apple" needs translation. # * msgid: the message id. # * Returns: msgid. def N_(msgsid) msgsid end def gettext(msgid, options = {}) I18n.t(msgid, { :default => msgid, :separator => '|' }.merge(options)) end alias _ gettext def sgettext(msgid, separator = '|') scope, msgid = I18n::Gettext.extract_scope(msgid, separator) I18n.t(msgid, :scope => scope, :default => msgid, :separator => separator) end alias s_ sgettext def pgettext(msgctxt, msgid) separator = I18n::Gettext::CONTEXT_SEPARATOR sgettext([msgctxt, msgid].join(separator), separator) end alias p_ pgettext def ngettext(msgid, msgid_plural, n = 1) nsgettext(msgid, msgid_plural, n) end alias n_ ngettext # Method signatures: # nsgettext('Fruits|apple', 'apples', 2) # nsgettext(['Fruits|apple', 'apples'], 2) def nsgettext(msgid, msgid_plural, n = 1, separator = '|') if msgid.is_a?(Array) msgid, msgid_plural, n, separator = msgid[0], msgid[1], msgid_plural, n separator = '|' unless separator.is_a?(::String) end scope, msgid = I18n::Gettext.extract_scope(msgid, separator) default = { :one => msgid, :other => msgid_plural } I18n.t(msgid, :default => default, :count => n, :scope => scope, :separator => separator) end alias ns_ nsgettext # Method signatures: # npgettext('Fruits', 'apple', 'apples', 2) # npgettext('Fruits', ['apple', 'apples'], 2) def npgettext(msgctxt, msgid, msgid_plural, n = 1) separator = I18n::Gettext::CONTEXT_SEPARATOR if msgid.is_a?(Array) msgid_plural, msgid, n = msgid[1], [msgctxt, msgid[0]].join(separator), msgid_plural else msgid = [msgctxt, msgid].join(separator) end nsgettext(msgid, msgid_plural, n, separator) end alias np_ npgettext end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/gettext/po_parser.rb
_vendor/ruby/2.6.0/gems/i18n-0.9.5/lib/i18n/gettext/po_parser.rb
=begin poparser.rb - Generate a .mo Copyright (C) 2003-2009 Masao Mutoh <mutoh at highway.ne.jp> You may redistribute it and/or modify it under the same license terms as Ruby. =end #MODIFIED # removed include GetText etc # added stub translation method _(x) require 'racc/parser' module GetText class PoParser < Racc::Parser def _(x) x end module_eval <<'..end src/poparser.ry modeval..id7a99570e05', 'src/poparser.ry', 108 def unescape(orig) ret = orig.gsub(/\\n/, "\n") ret.gsub!(/\\t/, "\t") ret.gsub!(/\\r/, "\r") ret.gsub!(/\\"/, "\"") ret end def parse(str, data, ignore_fuzzy = true) @comments = [] @data = data @fuzzy = false @msgctxt = "" $ignore_fuzzy = ignore_fuzzy str.strip! @q = [] until str.empty? do case str when /\A\s+/ str = $' when /\Amsgctxt/ @q.push [:MSGCTXT, $&] str = $' when /\Amsgid_plural/ @q.push [:MSGID_PLURAL, $&] str = $' when /\Amsgid/ @q.push [:MSGID, $&] str = $' when /\Amsgstr/ @q.push [:MSGSTR, $&] str = $' when /\A\[(\d+)\]/ @q.push [:PLURAL_NUM, $1] str = $' when /\A\#~(.*)/ $stderr.print _("Warning: obsolete msgid exists.\n") $stderr.print " #{$&}\n" @q.push [:COMMENT, $&] str = $' when /\A\#(.*)/ @q.push [:COMMENT, $&] str = $' when /\A\"(.*)\"/ @q.push [:STRING, $1] str = $' else #c = str[0,1] #@q.push [:STRING, c] str = str[1..-1] end end @q.push [false, '$end'] if $DEBUG @q.each do |a,b| puts "[#{a}, #{b}]" end end @yydebug = true if $DEBUG do_parse if @comments.size > 0 @data.set_comment(:last, @comments.join("\n")) end @data end def next_token @q.shift end def on_message(msgid, msgstr) if msgstr.size > 0 @data[msgid] = msgstr @data.set_comment(msgid, @comments.join("\n")) end @comments.clear @msgctxt = "" end def on_comment(comment) @fuzzy = true if (/fuzzy/ =~ comment) @comments << comment end ..end src/poparser.ry modeval..id7a99570e05 ##### racc 1.4.5 generates ### racc_reduce_table = [ 0, 0, :racc_error, 0, 10, :_reduce_none, 2, 10, :_reduce_none, 2, 10, :_reduce_none, 2, 10, :_reduce_none, 2, 12, :_reduce_5, 1, 13, :_reduce_none, 1, 13, :_reduce_none, 4, 15, :_reduce_8, 5, 16, :_reduce_9, 2, 17, :_reduce_10, 1, 17, :_reduce_none, 3, 18, :_reduce_12, 1, 11, :_reduce_13, 2, 14, :_reduce_14, 1, 14, :_reduce_15 ] racc_reduce_n = 16 racc_shift_n = 26 racc_action_table = [ 3, 13, 5, 7, 9, 15, 16, 17, 20, 17, 13, 17, 13, 13, 11, 17, 23, 20, 13, 17 ] racc_action_check = [ 1, 16, 1, 1, 1, 12, 12, 12, 18, 18, 7, 14, 15, 9, 3, 19, 20, 21, 23, 25 ] racc_action_pointer = [ nil, 0, nil, 14, nil, nil, nil, 3, nil, 6, nil, nil, 0, nil, 4, 5, -6, nil, 2, 8, 8, 11, nil, 11, nil, 12 ] racc_action_default = [ -1, -16, -2, -16, -3, -13, -4, -16, -6, -16, -7, 26, -16, -15, -5, -16, -16, -14, -16, -8, -16, -9, -11, -16, -10, -12 ] racc_goto_table = [ 12, 22, 14, 4, 24, 6, 2, 8, 18, 19, 10, 21, 1, nil, nil, nil, 25 ] racc_goto_check = [ 5, 9, 5, 3, 9, 4, 2, 6, 5, 5, 7, 8, 1, nil, nil, nil, 5 ] racc_goto_pointer = [ nil, 12, 5, 2, 4, -7, 6, 9, -7, -17 ] racc_goto_default = [ nil, nil, nil, nil, nil, nil, nil, nil, nil, nil ] racc_token_table = { false => 0, Object.new => 1, :COMMENT => 2, :MSGID => 3, :MSGCTXT => 4, :MSGID_PLURAL => 5, :MSGSTR => 6, :STRING => 7, :PLURAL_NUM => 8 } racc_use_result_var = true racc_nt_base = 9 Racc_arg = [ racc_action_table, racc_action_check, racc_action_default, racc_action_pointer, racc_goto_table, racc_goto_check, racc_goto_default, racc_goto_pointer, racc_nt_base, racc_reduce_table, racc_token_table, racc_shift_n, racc_reduce_n, racc_use_result_var ] Racc_token_to_s_table = [ '$end', 'error', 'COMMENT', 'MSGID', 'MSGCTXT', 'MSGID_PLURAL', 'MSGSTR', 'STRING', 'PLURAL_NUM', '$start', 'msgfmt', 'comment', 'msgctxt', 'message', 'string_list', 'single_message', 'plural_message', 'msgstr_plural', 'msgstr_plural_line'] Racc_debug_parser = true ##### racc system variables end ##### # reduce 0 omitted # reduce 1 omitted # reduce 2 omitted # reduce 3 omitted # reduce 4 omitted module_eval <<'.,.,', 'src/poparser.ry', 25 def _reduce_5( val, _values, result ) @msgctxt = unescape(val[1]) + "\004" result end .,., # reduce 6 omitted # reduce 7 omitted module_eval <<'.,.,', 'src/poparser.ry', 48 def _reduce_8( val, _values, result ) if @fuzzy and $ignore_fuzzy if val[1] != "" $stderr.print _("Warning: fuzzy message was ignored.\n") $stderr.print " msgid '#{val[1]}'\n" else on_message('', unescape(val[3])) end @fuzzy = false else on_message(@msgctxt + unescape(val[1]), unescape(val[3])) end result = "" result end .,., module_eval <<'.,.,', 'src/poparser.ry', 65 def _reduce_9( val, _values, result ) if @fuzzy and $ignore_fuzzy if val[1] != "" $stderr.print _("Warning: fuzzy message was ignored.\n") $stderr.print "msgid = '#{val[1]}\n" else on_message('', unescape(val[3])) end @fuzzy = false else on_message(@msgctxt + unescape(val[1]) + "\000" + unescape(val[3]), unescape(val[4])) end result = "" result end .,., module_eval <<'.,.,', 'src/poparser.ry', 76 def _reduce_10( val, _values, result ) if val[0].size > 0 result = val[0] + "\000" + val[1] else result = "" end result end .,., # reduce 11 omitted module_eval <<'.,.,', 'src/poparser.ry', 84 def _reduce_12( val, _values, result ) result = val[2] result end .,., module_eval <<'.,.,', 'src/poparser.ry', 91 def _reduce_13( val, _values, result ) on_comment(val[0]) result end .,., module_eval <<'.,.,', 'src/poparser.ry', 99 def _reduce_14( val, _values, result ) result = val.delete_if{|item| item == ""}.join result end .,., module_eval <<'.,.,', 'src/poparser.ry', 103 def _reduce_15( val, _values, result ) result = val[0] result end .,., def _reduce_none( val, _values, result ) result end end # class PoParser end # module GetText
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/pathutil-0.16.2/lib/pathutil.rb
_vendor/ruby/2.6.0/gems/pathutil-0.16.2/lib/pathutil.rb
# Frozen-string-literal: true # Copyright: 2015 - 2017 Jordon Bedwell - MIT License # Encoding: utf-8 require "pathutil/helpers" require "forwardable/extended" require "find" class Pathutil attr_writer :encoding extend Forwardable::Extended extend Helpers # -- # @note A lot of this class can be compatible with Pathname. # Initialize a new instance. # @return Pathutil # -- def initialize(path) return @path = path if path.is_a?(String) return @path = path.to_path if path.respond_to?(:to_path) return @path = path.to_s end # -- # Make a path relative. # -- def relative return self if relative? self.class.new(strip_windows_drive.gsub( %r!\A(\\+|/+)!, "" )) end # -- # Make a path absolute # -- def absolute return self if absolute? self.class.new("/").join( @path ) end # -- # @see Pathname#cleanpath. # @note This is a wholesale rip and cleanup of Pathname#cleanpath # @return Pathutil # -- def cleanpath(symlink = false) symlink ? conservative_cleanpath : aggressive_cleanpath end # -- # @yield Pathutil # @note It will return all results that it finds across all ascending paths. # @example Pathutil.new("~/").expand_path.search_backwards(".bashrc") => [#<Pathutil:/home/user/.bashrc>] # Search backwards for a file (like Rakefile, _config.yml, opts.yml). # @return Enum # -- def search_backwards(file, backwards: Float::INFINITY) ary = [] ascend.with_index(1).each do |path, index| if index > backwards break else Dir.chdir path do if block_given? file = self.class.new(file) if yield(file) ary.push( file ) end elsif File.exist?(file) ary.push(self.class.new( path.join(file) )) end end end end ary end # -- # Read the file as a YAML file turning it into an object. # @see self.class.load_yaml as this a direct alias of that method. # @return Hash # -- def read_yaml(throw_missing: false, **kwd) self.class.load_yaml( read, **kwd ) rescue Errno::ENOENT throw_missing ? raise : ( return {} ) end # -- # Read the file as a JSON file turning it into an object. # @see self.class.read_json as this is a direct alias of that method. # @return Hash # -- def read_json(throw_missing: false) JSON.parse( read ) rescue Errno::ENOENT throw_missing ? raise : ( return {} ) end # -- # @note The blank part is intentionally left there so that you can rejoin. # Splits the path into all parts so that you can do step by step comparisons # @example Pathutil.new("/my/path").split_path # => ["", "my", "path"] # @return Array<String> # -- def split_path @path.split( %r!\\+|/+! ) end # -- # @see `String#==` for more details. # A stricter version of `==` that also makes sure the object matches. # @return true|false # -- def ===(other) other.is_a?(self.class) && @path == other end # -- # @example Pathutil.new("/hello") >= Pathutil.new("/") # => true # @example Pathutil.new("/hello") >= Pathutil.new("/hello") # => true # Checks to see if a path falls within a path and deeper or is the other. # @return true|false # -- def >=(other) mine, other = expanded_paths(other) return true if other == mine mine.in_path?(other) end # -- # @example Pathutil.new("/hello/world") > Pathutil.new("/hello") # => true # Strictly checks to see if a path is deeper but within the path of the other. # @return true|false # -- def >(other) mine, other = expanded_paths(other) return false if other == mine mine.in_path?(other) end # -- # @example Pathutil.new("/") < Pathutil.new("/hello") # => true # Strictly check to see if a path is behind other path but within it. # @return true|false # -- def <(other) mine, other = expanded_paths(other) return false if other == mine other.in_path?(mine) end # -- # Check to see if a path is behind the other path but within it. # @example Pathutil.new("/hello") < Pathutil.new("/hello") # => true # @example Pathutil.new("/") < Pathutil.new("/hello") # => true # @return true|false # -- def <=(other) mine, other = expanded_paths(other) return true if other == mine other.in_path?(mine) end # -- # @note "./" is considered relative. # Check to see if the path is absolute, as in: starts with "/" # @return true|false # -- def absolute? return !!( @path =~ %r!\A(?:[A-Za-z]:)?(?:\\+|/+)! ) end # -- # @yield Pathutil # Break apart the path and yield each with the previous parts. # @example Pathutil.new("/hello/world").ascend.to_a # => ["/", "/hello", "/hello/world"] # @example Pathutil.new("/hello/world").ascend { |path| $stdout.puts path } # @return Enum # -- def ascend unless block_given? return to_enum( __method__ ) end yield( path = self ) while (new_path = path.dirname) if path == new_path || new_path == "." break else path = new_path yield new_path end end nil end # -- # @yield Pathutil # Break apart the path in reverse order and descend into the path. # @example Pathutil.new("/hello/world").descend.to_a # => ["/hello/world", "/hello", "/"] # @example Pathutil.new("/hello/world").descend { |path| $stdout.puts path } # @return Enum # -- def descend unless block_given? return to_enum( __method__ ) end ascend.to_a.reverse_each do |val| yield val end nil end # -- # @yield Pathutil # @example Pathutil.new("/hello/world").each_line { |line| $stdout.puts line } # Wraps `readlines` and allows you to yield on the result. # @return Enum # -- def each_line return to_enum(__method__) unless block_given? readlines.each do |line| yield line end nil end # -- # @example Pathutil.new("/hello").fnmatch?("/hello") # => true # Unlike traditional `fnmatch`, with this one `Regexp` is allowed. # @example Pathutil.new("/hello").fnmatch?(/h/) # => true # @see `File#fnmatch` for more information. # @return true|false # -- def fnmatch?(matcher) matcher.is_a?(Regexp) ? !!(self =~ matcher) : \ File.fnmatch(matcher, self) end # -- # Allows you to quickly determine if the file is the root folder. # @return true|false # -- def root? !!(self =~ %r!\A(?:[A-Za-z]:)?(?:\\+|/+)\z!) end # -- # Allows you to check if the current path is in the path you want. # @return true|false # -- def in_path?(path) path = self.class.new(path).expand_path.split_path mine = (symlink?? expand_path.realpath : expand_path).split_path path.each_with_index { |part, index| return false if mine[index] != part } true end # -- def inspect "#<#{self.class}:#{@path}>" end # -- # @return Array<Pathutil> # Grab all of the children from the current directory, including hidden. # @yield Pathutil # -- def children ary = [] Dir.foreach(@path) do |path| if path == "." || path == ".." next else path = self.class.new(File.join(@path, path)) yield path if block_given? ary.push( path ) end end ary end # -- # @yield Pathutil # Allows you to glob however you wish to glob in the current `Pathutil` # @see `File::Constants` for a list of flags. # @return Enum # -- def glob(pattern, flags = 0) unless block_given? return to_enum( __method__, pattern, flags ) end chdir do Dir.glob(pattern, flags).each do |file| yield self.class.new( File.join(@path, file) ) end end nil end # -- # @yield &block # Move to the current directory temporarily (or for good) and do work son. # @note you do not need to ship a block at all. # @return nil # -- def chdir if !block_given? Dir.chdir( @path ) else Dir.chdir @path do yield end end end # -- # @yield Pathutil # Find all files without care and yield the given block. # @return Enum # -- def find return to_enum(__method__) unless block_given? Find.find @path do |val| yield self.class.new(val) end end # -- # @yield Pathutil # Splits the path returning each part (filename) back to you. # @return Enum # -- def each_filename return to_enum(__method__) unless block_given? @path.split(File::SEPARATOR).delete_if(&:empty?).each do |file| yield file end end # -- # Get the parent of the current path. # @note This will simply return self if "/". # @return Pathutil # -- def parent return self if @path == "/" self.class.new(absolute?? File.dirname(@path) : File.join( @path, ".." )) end # -- # @yield Pathutil # Split the file into its dirname and basename, so you can do stuff. # @return nil # -- def split File.split(@path).collect! do |path| self.class.new(path) end end # -- # @note Your extension should start with "." # Replace a files extension with your given extension. # @return Pathutil # -- def sub_ext(ext) self.class.new(@path.chomp(File.extname(@path)) + ext) end # -- # A less complex version of `relative_path_from` that simply uses a # `Regexp` and returns the full path if it cannot be determined. # @return Pathutil # -- def relative_path_from(from) from = self.class.new(from).expand_path.gsub(%r!/$!, "") self.class.new(expand_path.gsub(%r!^#{ from.regexp_escape }/!, "")) end # -- # Expands the path and left joins the root to the path. # @return Pathutil # -- def enforce_root(root) return self if !relative? && in_path?(root) self.class.new(root).join( self ) end # -- # Copy a directory, allowing symlinks if the link falls inside of the root. # This is indented for people who wish some safety to their copies. # @note Ignore is ignored on safe_copy file because it's explicit. # @return nil # -- def safe_copy(to, root: nil, ignore: []) raise ArgumentError, "must give a root" unless root root = self.class.new(root) to = self.class.new(to) if directory? safe_copy_directory(to, { :root => root, :ignore => ignore }) else safe_copy_file(to, { :root => root }) end end # -- # @see `self.class.normalize` as this is an alias. # -- def normalize return @normalize ||= begin self.class.normalize end end # -- # @see `self.class.encoding` as this is an alias. # -- def encoding return @encoding ||= begin self.class.encoding end end # -- # @note You can set the default encodings via the class. # Read took two steroid shots: it can normalize your string, and encode. # @return String # -- def read(*args, **kwd) kwd[:encoding] ||= encoding if normalize[:read] File.read(self, *args, kwd).encode({ :universal_newline => true }) else File.read( self, *args, kwd ) end end # -- # @note You can set the default encodings via the class. # Binread took two steroid shots: it can normalize your string, and encode. # @return String # -- def binread(*args, **kwd) kwd[:encoding] ||= encoding if normalize[:read] File.binread(self, *args, kwd).encode({ :universal_newline => true }) else File.read( self, *args, kwd ) end end # -- # @note You can set the default encodings via the class. # Readlines took two steroid shots: it can normalize your string, and encode. # @return Array<String> # -- def readlines(*args, **kwd) kwd[:encoding] ||= encoding if normalize[:read] File.readlines(self, *args, kwd).encode({ :universal_newline => true }) else File.readlines( self, *args, kwd ) end end # -- # @note You can set the default encodings via the class. # Write took two steroid shots: it can normalize your string, and encode. # @return Fixnum<Bytes> # -- def write(data, *args, **kwd) kwd[:encoding] ||= encoding if normalize[:write] File.write(self, data.encode( :crlf_newline => true ), *args, kwd) else File.write( self, data, *args, kwd ) end end # -- # @note You can set the default encodings via the class. # Binwrite took two steroid shots: it can normalize your string, and encode. # @return Fixnum<Bytes> # -- def binwrite(data, *args, **kwd) kwd[:encoding] ||= encoding if normalize[:write] File.binwrite(self, data.encode( :crlf_newline => true ), *args, kwd) else File.binwrite( self, data, *args, kwd ) end end # -- def to_regexp(guard: true) Regexp.new((guard ? "\\A" : "") + Regexp.escape( self )) end # -- # Strips the windows drive from the path. # -- def strip_windows_drive(path = @path) self.class.new(path.gsub( %r!\A[A-Za-z]:(?:\\+|/+)!, "" )) end # -- # rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/CyclomaticComplexity # rubocop:disable Metrics/PerceivedComplexity # -- def aggressive_cleanpath return self.class.new("/") if root? _out = split_path.each_with_object([]) do |part, out| next if part == "." || (part == ".." && out.last == "") if part == ".." && out.last && out.last != ".." out.pop else out.push( part ) end end # -- return self.class.new("/") if _out == [""].freeze return self.class.new(".") if _out.empty? && (end_with?(".") || relative?) self.class.new(_out.join("/")) end # -- def conservative_cleanpath _out = split_path.each_with_object([]) do |part, out| next if part == "." || (part == ".." && out.last == "") out.push( part ) end # -- if !_out.empty? && basename == "." && _out.last != "" && _out.last != ".." _out << "." end # -- return self.class.new("/") if _out == [""].freeze return self.class.new(".") if _out.empty? && (end_with?(".") || relative?) return self.class.new(_out.join("/")).join("") if @path =~ %r!/\z! \ && _out.last != "." && _out.last != ".." self.class.new(_out.join("/")) end # -- # rubocop:enable Metrics/AbcSize # rubocop:enable Metrics/CyclomaticComplexity # rubocop:enable Metrics/PerceivedComplexity # Expand the paths and return. # -- private def expanded_paths(path) return expand_path, self.class.new(path).expand_path end # -- # Safely copy a file. # -- private def safe_copy_file(to, root: nil) raise Errno::EPERM, "#{self} not in #{root}" unless in_path?(root) FileUtils.cp(self, to, { :preserve => true }) end # -- # Safely copy a directory and it's sub-files. # -- private def safe_copy_directory(to, root: nil, ignore: []) ignore = [ignore].flatten.uniq if !in_path?(root) raise Errno::EPERM, "#{self} not in #{ root }" else to.mkdir_p unless to.exist? children do |file| unless ignore.any? { |path| file.in_path?(path) } if !file.in_path?(root) raise Errno::EPERM, "#{file} not in #{ root }" elsif file.file? FileUtils.cp(file, to, { :preserve => true }) else path = file.realpath path.safe_copy(to.join(file.basename), { :root => root, :ignore => ignore }) end end end end end class << self attr_writer :encoding # -- # @note We do nothing special here. # Get the current directory that Ruby knows about. # @return Pathutil # -- def pwd new( Dir.pwd ) end alias gcwd pwd alias cwd pwd # -- # @note you are encouraged to override this if you need to. # Aliases the default system encoding to us so that we can do most read # and write operations with that encoding, instead of being crazy. # -- def encoding return @encoding ||= begin Encoding.default_external end end # -- # Normalize CRLF -> LF on Windows reads, to ease your troubles. # Normalize LF -> CLRF on Windows write, to ease your troubles. # -- def normalize return @normalize ||= { :read => Gem.win_platform?, :write => Gem.win_platform? } end # -- # Make a temporary directory. # @note if you adruptly exit it will not remove the dir. # @note this directory is removed on exit. # @return Pathutil # -- def tmpdir(*args) rtn = new(make_tmpname(*args)).tap(&:mkdir) ObjectSpace.define_finalizer(rtn, proc do rtn.rm_rf end) rtn end # -- # Make a temporary file. # @note if you adruptly exit it will not remove the dir. # @note this file is removed on exit. # @return Pathutil # -- def tmpfile(*args) rtn = new(make_tmpname(*args)).tap(&:touch) ObjectSpace.define_finalizer(rtn, proc do rtn.rm_rf end) rtn end end # -- rb_delegate :gcwd, :to => :"self.class" rb_delegate :pwd, :to => :"self.class" # -- rb_delegate :sub, :to => :@path, :wrap => true rb_delegate :chomp, :to => :@path, :wrap => true rb_delegate :gsub, :to => :@path, :wrap => true rb_delegate :[], :to => :@path rb_delegate :=~, :to => :@path rb_delegate :==, :to => :@path rb_delegate :to_s, :to => :@path rb_delegate :freeze, :to => :@path rb_delegate :end_with?, :to => :@path rb_delegate :start_with?, :to => :@path rb_delegate :frozen?, :to => :@path rb_delegate :to_str, :to => :@path rb_delegate :"!~", :to => :@path rb_delegate :<=>, :to => :@path # -- rb_delegate :chmod, :to => :File, :args => { :after => :@path } rb_delegate :lchown, :to => :File, :args => { :after => :@path } rb_delegate :lchmod, :to => :File, :args => { :after => :@path } rb_delegate :chown, :to => :File, :args => { :after => :@path } rb_delegate :basename, :to => :File, :args => :@path, :wrap => true rb_delegate :dirname, :to => :File, :args => :@path, :wrap => true rb_delegate :readlink, :to => :File, :args => :@path, :wrap => true rb_delegate :expand_path, :to => :File, :args => :@path, :wrap => true rb_delegate :realdirpath, :to => :File, :args => :@path, :wrap => true rb_delegate :realpath, :to => :File, :args => :@path, :wrap => true rb_delegate :rename, :to => :File, :args => :@path, :wrap => true rb_delegate :join, :to => :File, :args => :@path, :wrap => true rb_delegate :empty?, :to => :file, :args => :@path rb_delegate :size, :to => :File, :args => :@path rb_delegate :link, :to => :File, :args => :@path rb_delegate :atime, :to => :File, :args => :@path rb_delegate :ctime, :to => :File, :args => :@path rb_delegate :lstat, :to => :File, :args => :@path rb_delegate :utime, :to => :File, :args => :@path rb_delegate :sysopen, :to => :File, :args => :@path rb_delegate :birthtime, :to => :File, :args => :@path rb_delegate :mountpoint?, :to => :File, :args => :@path rb_delegate :truncate, :to => :File, :args => :@path rb_delegate :symlink, :to => :File, :args => :@path rb_delegate :extname, :to => :File, :args => :@path rb_delegate :zero?, :to => :File, :args => :@path rb_delegate :ftype, :to => :File, :args => :@path rb_delegate :mtime, :to => :File, :args => :@path rb_delegate :open, :to => :File, :args => :@path rb_delegate :stat, :to => :File, :args => :@path # -- rb_delegate :pipe?, :to => :FileTest, :args => :@path rb_delegate :file?, :to => :FileTest, :args => :@path rb_delegate :owned?, :to => :FileTest, :args => :@path rb_delegate :setgid?, :to => :FileTest, :args => :@path rb_delegate :socket?, :to => :FileTest, :args => :@path rb_delegate :readable?, :to => :FileTest, :args => :@path rb_delegate :blockdev?, :to => :FileTest, :args => :@path rb_delegate :directory?, :to => :FileTest, :args => :@path rb_delegate :readable_real?, :to => :FileTest, :args => :@path rb_delegate :world_readable?, :to => :FileTest, :args => :@path rb_delegate :executable_real?, :to => :FileTest, :args => :@path rb_delegate :world_writable?, :to => :FileTest, :args => :@path rb_delegate :writable_real?, :to => :FileTest, :args => :@path rb_delegate :executable?, :to => :FileTest, :args => :@path rb_delegate :writable?, :to => :FileTest, :args => :@path rb_delegate :grpowned?, :to => :FileTest, :args => :@path rb_delegate :chardev?, :to => :FileTest, :args => :@path rb_delegate :symlink?, :to => :FileTest, :args => :@path rb_delegate :sticky?, :to => :FileTest, :args => :@path rb_delegate :setuid?, :to => :FileTest, :args => :@path rb_delegate :exist?, :to => :FileTest, :args => :@path rb_delegate :size?, :to => :FileTest, :args => :@path # -- rb_delegate :rm_rf, :to => :FileUtils, :args => :@path rb_delegate :rm_r, :to => :FileUtils, :args => :@path rb_delegate :rm_f, :to => :FileUtils, :args => :@path rb_delegate :rm, :to => :FileUtils, :args => :@path rb_delegate :cp_r, :to => :FileUtils, :args => :@path rb_delegate :touch, :to => :FileUtils, :args => :@path rb_delegate :mkdir_p, :to => :FileUtils, :args => :@path rb_delegate :mkpath, :to => :FileUtils, :args => :@path rb_delegate :cp, :to => :FileUtils, :args => :@path # -- rb_delegate :each_child, :to => :children rb_delegate :each_entry, :to => :children rb_delegate :to_a, :to => :children # -- rb_delegate :opendir, :to => :Dir, :alias_of => :open rb_delegate :relative?, :to => :self, :alias_of => :absolute?, :bool => :reverse rb_delegate :regexp_escape, :to => :Regexp, :args => :@path, :alias_of => :escape rb_delegate :shellescape, :to => :Shellwords, :args => :@path rb_delegate :mkdir, :to => :Dir, :args => :@path # -- alias + join alias delete rm alias rmtree rm_r alias to_path to_s alias last basename alias entries children alias make_symlink symlink alias cleanpath_conservative conservative_cleanpath alias cleanpath_aggressive aggressive_cleanpath alias prepend enforce_root alias fnmatch fnmatch? alias make_link link alias first dirname alias rmdir rm_r alias unlink rm alias / join end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false