Class: Worldwide::Names

Inherits:
Object
  • Object
show all
Defined in:
lib/worldwide/names.rb

Class Method Summary collapse

Class Method Details

.abbreviated(given:, surname:, ideal_max_length: 3) ⇒ Object



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
# File 'lib/worldwide/names.rb', line 33

def abbreviated(given:, surname:, ideal_max_length: 3)
  given_stripped = given&.strip
  surname_stripped = surname&.strip

  combined_name = given_stripped.to_s + surname_stripped.to_s
  return if combined_name.blank? || combined_name.match?(/[\p{Punctuation}\s]/)
  return unless ideal_max_length.is_a?(Integer) && ideal_max_length.positive?

  scripts = Scripts.identify(text: combined_name)
  return unless scripts.length == 1

  given_clusters = given_stripped&.grapheme_clusters
  surname_clusters = surname_stripped&.grapheme_clusters

  # Scripts that Scripts.identify recognizes but that have no abbreviation rule
  # here (e.g. Arabic) intentionally return nil so callers fall back to a greeting.
  case scripts.first
  when :Latin
    [given_stripped, surname_stripped].reject(&:blank?).map { |name| name[0] }.join
  when :Han, :Katakana, :Hiragana
    surname_stripped.presence
  when :Hangul
    if given_stripped.blank?
      surname_stripped
    elsif given_clusters.length > ideal_max_length
      given_clusters[0]
    else
      given_stripped
    end
  when :Thai
    if given_stripped.present?
      given_clusters[0]
    elsif surname_stripped.present?
      surname_clusters[0]
    end
  end
end

.full(given:, surname:) ⇒ Object



15
16
17
# File 'lib/worldwide/names.rb', line 15

def full(given:, surname:)
  format_name("full", given, surname)
end

.greeting(given:, surname:) ⇒ Object



19
20
21
# File 'lib/worldwide/names.rb', line 19

def greeting(given:, surname:)
  format_name("greeting", given, surname)
end

.initials(given:, surname:) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/worldwide/names.rb', line 23

def initials(given:, surname:)
  return if given.nil? && surname.nil?

  names = [given, surname].reject(&:blank?).select do |name|
    I18n.transliterate(name[0]) =~ /[a-zA-Z]/
  end

  names.map { |name| name[0] }
end

.surname_first?(locale) ⇒ Boolean

Returns:

  • (Boolean)


9
10
11
12
13
# File 'lib/worldwide/names.rb', line 9

def surname_first?(locale)
  return false if locale.nil?

  SURNAME_FIRST_LOCALES.include?(language_subtag(locale))
end