There's already an accepted answer for this but I thought I'd share what I did that solved this problem without using any Rails stuff. It accounts for ::
in the class names and everything.
def self.humanize_class_name
self.inspect.scan(/[A-Z][a-z]+/).join(' ')
end
What this does is takes the stringified class name (self.inspect
) and then .scan
creates an array of any strings of characters within that class name that match the regexes, which join
then joins into a single string, placing a space between each word. In this case, the regex /[A-Z][a-z]+/
selects all strings in the word that consist of a single capital letter followed by one or more lower-case letters.
You'd have to modify the regex if any of your class names contained multiple consecutive capital letters, especially if the consecutive capitals could belong to different words (e.g., a class called MyJSONParser
should be humanised as "My JSON Parser", whereas the regex above would render it as "My Parser" since the consecutive capitals would be ignored).
Note that the method as I've written it also assumes it is a class method. An instance method would look like this:
def humanize_class_name
self.class.inspect.scan(/[A-Z][a-z]+/).join(' ')
end
I hope this is helpful to someone!