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?

1 Answer 1

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.

3
  • 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? Jul 17, 2012 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, 2012 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 ? Jul 18, 2012 at 0:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.