Module: StringMagic::Core::Transformation

Included in:
StringMagic
Defined in:
lib/string_magic/core/transformation.rb

Instance Method Summary collapse

Instance Method Details

#titleize_names(text) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/string_magic/core/transformation.rb', line 4

def titleize_names(text)
  return text if text.nil? || text.empty?

  special_cases = {
    "mcdonald" => "McDonald",
    "o'reilly" => "O'Reilly",
    "macbook" => "MacBook",
    "iphone" => "iPhone",
    "ipad" => "iPad",
    "ebay" => "eBay"
  }

  prefixes = Set.new(%w[van de la du das dos di da delle degli delle])
  articles = Set.new(%w[a an the]) # Add this line

  words = text.downcase.split(/\s+/)
  words.map.with_index do |word, index|
    if special_cases.key?(word)
      special_cases[word]
    elsif prefixes.include?(word) && !index.zero?
      word
    elsif articles.include?(word) && !index.zero? # Add this condition
      word.downcase
    else
      word.capitalize
    end
  end.join(" ")
end

#to_kebab_case(string) ⇒ Object



42
43
44
# File 'lib/string_magic/core/transformation.rb', line 42

def to_kebab_case(string)
  to_snake_case(string).tr("_", "-")
end

#to_pascal_case(string) ⇒ Object



46
47
48
49
50
51
# File 'lib/string_magic/core/transformation.rb', line 46

def to_pascal_case(string)
  return "" if string.nil?
  return string if string.match?(/^[A-Z][a-z]*([A-Z][a-z]*)*$/)

  string.split(/[-_\s]+/).map(&:capitalize).join
end

#to_snake_case(string) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/string_magic/core/transformation.rb', line 33

def to_snake_case(string)
  return "" if string.nil?

  string.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
        .gsub(/([a-z\d])([A-Z])/, '\1_\2')
        .tr("-", "_")
        .downcase
end