views:

52

answers:

2

Here's an easy one:

How do I go about setting the default format for a string field in ActiveRecord?

I've tried the following:

def phone_number_f
  "...#{phone_number}format_here..."
end

But I'd like to keep the method name the same as the field name.

+3  A: 

Not sure exactly what you're looking for, but I'm guessing it's this.

def phone_number
  "...#{read_attribute(:phone_number)}format_here..."
end
Mike
You got it Mike, thanks!
btelles
+1  A: 

Are you looking to store things in a specific format or output them in a specific format.

Unless you have to do calculations on things it makes more sense to put data in the correct format before storing it in the database. That way you only ever need to convert it once.

The best way to do that is with a before_validate callback to put things in the proper format if it isn't already. Use it in tandem with the validates_format_of helper to ensure that it worked. You may have been passed data that cannot be massaged into the format you want.

If you do need to perform calculations and may need to change output formatting, you can use the formatter callback method as a formatting string. You may want to look into String#sub, String#unpack and Kernel#sprintf/String#%.

North American Phone number example: The regular expression could be wrong, but that's not the important part of the example.

before_validate :fix_phone_number_format

def fix_phone_number_format
  self.phone_number = "(%s) %s-%s" % phone_number.gsub(/[\D]/, "").unpack("A3A3A4")
end

validates_format_of :phone_number, :with => /^(\d{3}) \d{3}-\d{4}/

EDIT: the conversion is slightly complicated, so here's a step by step breakdown as as ruby does things. With phone number given as 123-555-1234.

"(%s) %s-%s" % phone_number.gsub(/[\D]/, "").unpack("A3A3A4")
"(%s) %s-%s" % "123-555-1234".gsub(/[\D]/, "").unpack("A3A3A4")

# remove all non digits from the string
"(%s) %s-%s" % "1235551234".unpack("A3A3A4")

# break the string up into an array of three pieces.
# Such that the first element is the first 3 characters in the string,
# the second element is 4th through 6th characters in the string,
# and the third element is the remaining digits.
"(%s) %s-%s" % ["123","555","1234"]

# Apply the format string to the array.
"(123) 555-1234"
EmFi
Vedy Innteresting...thanks! Although Mike answered the question at hand, your argument about storing data in the correct format certainly makes more sense in terms of resources, and I will follow your advice. Thanks EmFi
btelles