Reputation: 11336
I'm saving phone numbers as domestic on a phone
field on a User
model.
I did a quick method to convert the number to international.
My question is how to make this method available like this
@user.phone.to_international
Rather than my current
to_international(@user.phone.to_international,@user.phone.country)
Any idea how to do accomplish this?
Upvotes: 0
Views: 454
Reputation: 9014
Monkey patch the String
class. In myapp/config/initializers/string_monkey_patches.rb
add:
String.class_eval do
PHONE_NUMBER_FORMAT = // # some regex matching a phone number
def to_international
raise 'Invalid phone number format' unless self.match(PHONE_NUMBER_FORMAT)
# convert self (the phone number string) to an international number
end
end
Upvotes: -1
Reputation:
Create a class called phone with a to_international method, and set the phone property in the user class to be an instance of the phone class.
Upvotes: 2
Reputation: 16720
This works, but not sure if after_initialize is better or not
Add this to your User model
after_find :prepare_phone
private
def prepare_phone
def phone.to_international
self.upcase # change with whatever you want. 'self' is the phone attr
end
end
Upvotes: 2