I have an app that asks a user to enter a 10 digit phone number...
To make things easy for the user, the input field is a single text
box.
I'd like to turn whatever the user enters into xxx-xxx-xxxx whether
they enter xxxxxxxxxx or (xxx)xxx-xxxx or (xxx)xxxxxx you get the
idea...
Is there any code out there that does this already? With so many
consumer apps out there, I am sure I'm sure this problem has been
solved many times over
Indeed. This one does lots of things from dealing with single fields to dealing with three-field UIs. It also allows it to be displayed in a few formats.
It's one of the first Ruby things I wrote, so it's not entirely deconstructed to eliminate all redundancies, and may be some non-idiomatic stuff.
I use this as a composition in my models with supporting code like so:
def phone_number
PhoneNumber.new(super)
end
def phone_number=(phone)
super PhoneNumber.new(phone).to_s
end