Reputation: 824
I have a model called Organizations that contains fields for its address. In the model I have the statement before_save { self.address_line_1 = address_line_1.titleize }
and just realized this is changing addresses with PO Box to Po Box.
Another example: I also have a standard Users model with first name/last name. Titleize will change a person's first name from TJ to Tj. Or, if their last name is hyphenated it will go from Smith-Jones to Smith Jones.
With the PO box I would know the exception ahead of time, but not for user's names. Is there any way to allow for these exceptions at all while still having the core titlsize functionality?
Upvotes: 0
Views: 418
Reputation: 58244
I would recommend trying to avoid changing the semantics of titlelize
, though, to avoid issues later when you might expect it, in another part of the same application, to do what it's really intended to do. Since you're looking for some fairly specialized functionality for titleize
I'd create a new, similar method which you could monkey patch into the String
class, as above, called something like, abook_titleize
(address book titleize):
class String
def abook_titleize
if allow_titleize(self)
titleize
else
# Check for other behaviors, such as if "self" is all consonants
# or if self is found in a predetermined list of acronyms,
# perhaps return self.upcase
self.upcase
end
end
private
def allow_titleize(s)
# Write some code here that determines if you want this string
# to be titleized and return true if so, otherwise false
end
end
Or something like that. You could make this as simple or as elaborate as you wish. If you really want to change titleize
bahavior itself (again, I wouldn't recommend), then:
class String
:alias_method :old_titleize, :titleize
def titleize
if allow_titleize(self)
old_titleize
else
...
Upvotes: 1