如何干掉重复的Ruby代码?

时间:2013-08-29 18:17:42

标签: ruby-on-rails ruby coding-style dry code-cleanup

我对红宝石比较新。这可以被干掉吗?怎么样?

def primary_phone
  number_to_phone self.primary_phone_number
end

def primary_phone=(number)
  self.primary_phone_number = number.gsub(/\D/, '')
end

def secondary_phone
  number_to_phone self.secondary_phone_number
end

def secondary_phone=(number)
  self.secondary_phone_number = number.gsub(/\D/, '')
end

def fax
  number_to_phone self.fax_phone_number
end

def fax=(number)
  self.fax_phone_number = number.gsub(/\D/, '')
end

我在Rails中使用此代码作为数据库之间的一种缓冲区,它将数字存储为整数,以及将它们作为字符串输入的用户表单。

1 个答案:

答案 0 :(得分:7)

你需要的只是,

before_save :sanitize_phone_number_fields

def sanitize_phone_number_fields
  [:primary_phone, :secondary_phone, :fax].each{|attr| self.send(attr).gsub!(/\D/, '')}
end