Why does Rails titlecase add a space to a name?

前端 未结 10 1325
我在风中等你
我在风中等你 2021-02-05 10:28

Why does the titlecase mess up the name? I have:

John Mark McMillan

and it turns it into:

>> \"john mark McM         


        
10条回答
  •  醉酒成梦
    2021-02-05 10:45

    We have just added this which supports a few different cases that we face.

    class String
      # Default titlecase converts McKay to Mc Kay, which is not great
      # May even need to remove titlecase completely in the future to leave 
      # strings unchanged
      def self.custom_title_case(string = "")
        return "" if !string.is_a?(String) || string.empty?
    
        split = string.split(" ").collect do |word|
          word = word.titlecase
    
          # If we titlecase and it turns in to 2 words, then we need to merge back
          word = word.match?(/\w/) ? word.split(" ").join("") : word
          
          word
        end
        
        return split.join(" ")
      end
    end
    
    

    And the rspec test

    # spec/lib/modules/string_spec.rb
    require 'rails_helper'
    require 'modules/string'
    
    describe "String" do
      describe "self.custom_title_case" do
        it "returns empty string if incorrect params" do
          result_one = String.custom_title_case({ test: 'object' })
          result_two = String.custom_title_case([1, 2])
          result_three = String.custom_title_case()
    
          expect(result_one).to eq("")
          expect(result_two).to eq("")
          expect(result_three).to eq("")
        end
    
        it "returns string in title case" do
          result = String.custom_title_case("smiths hill")
          expect(result).to eq("Smiths Hill")
        end
    
        it "caters for 'Mc' i.e. 'john mark McMillan' edge cases" do
          result_one = String.custom_title_case("burger king McDonalds")
          result_two = String.custom_title_case("john mark McMillan")
          result_three = String.custom_title_case("McKay bay")
    
          expect(result_one).to eq("Burger King McDonalds")
          expect(result_two).to eq("John Mark McMillan")
          expect(result_three).to eq("McKay Bay")
        end
    
        it "correctly cases uppercase words" do
          result = String.custom_title_case("NORTH NARRABEEN")
          expect(result).to eq("North Narrabeen")
        end
      end
    end
    

提交回复
热议问题