2009-11-20 5 views

답변

3

당신이 찾고있는 것이 정확히 무엇인지 모르겠지만, 나는 이것이 이것을 추측하고 있습니다.

def phone_number 
    "...#{read_attribute(:phone_number)}format_here..." 
end 
+0

마이크, 고마워! – btelles

1

특정 형식으로 저장하거나 특정 형식으로 출력하려고합니다.

일에 계산을 수행해야하는 경우가 아니면 데이터를 데이터베이스에 저장하기 전에 올바른 형식으로 저장하는 것이 좋습니다. 그렇게하면 단 한번 변환해야합니다.

가장 좋은 방법은 before_validate 콜백을 사용하여 사물을 적절한 형식으로 저장하는 것입니다 (아직없는 경우). validates_format_of helper과 함께 사용하여 제대로 작동하는지 확인하십시오. 원하는 형식으로 마사지 할 수없는 데이터가 전달되었을 수 있습니다.

계산을 수행해야하고 출력 형식을 변경해야하는 경우 형식화 문자열로 형식화 콜백 메소드를 사용할 수 있습니다. String#sub, String#unpackKernel#sprintf/String#%을 살펴볼 수 있습니다.

북미 전화 번호 예 : 정규 표현식이 잘못되었지만 그 예가 중요하지 않습니다.

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}/ 

편집 : 변환이, 그래서 여기에 약간 복잡 루비는 일을 한 단계 고장 단계입니다. 전화 번호는 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" 
+0

Vedy 흥미 롭군요 ... 고마워요! Mike가 질문에 대답했지만 정확한 형식으로 데이터를 저장하는 것에 대한 귀하의 논거는 확실히 자원 측면에서 더 합리적입니다. 나는 귀하의 조언을 따를 것입니다. 감사 EmFi – btelles

관련 문제