0

Is there a way to override the .titleize method in RoR?

For example, titleize does not work for names like TJ Watson. It converts 'tj watson' to Tj Watson. I would like to add such rules to it.

Also, I don't want to define a new method because my code already uses .titleize through it. How can I add features to titleize without having to change the method calls throughout the code?

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
RailsTweeter
  • 1,625
  • 3
  • 18
  • 33

1 Answers1

2

Put some *.rb file in your initializers folder with the following content:

# encoding: utf-8

module ActiveSupport
  module Inflector
    def titleize(word)
      # old code for referencing:
      # humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
      < your code goes here >
    end
  end
end

Also check this approach: https://stackoverflow.com/a/10471857/1322562.

Community
  • 1
  • 1
jdoe
  • 15,665
  • 2
  • 46
  • 48
  • Question: When i do this code, I get the following: /config/initializers/inflections.rb:16: syntax error, unexpected $end, expecting ')' ...erscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize } ------- I'm assuming that this is due to encoding? How do i fix this? – RailsTweeter Jul 17 '12 at 11:24
  • Did you put the `# encoding: utf-8` line at the very beginning of your file? It's a magic comment. It has to be there. – jdoe Jul 17 '12 at 13:40
  • Great. I had to remove one of the apostrophe like characters for it to work. Question: if I wanted to leave dashes ( - ) in the string, how would I do that? For example, currently "james franklin-howard".titleize => "James Franklin Howard" ... how would I get James Franklin-Howard ? – RailsTweeter Jul 18 '12 at 00:44