[Rails] Formatting data drawn from a DB
Jean-François
jf.web3 at gmail.com
Tue Apr 18 22:08:09 GMT 2006
Jodi :
> >> protected
> >> def after_find
> >> self.phone = "#{self.phone_before_type_cast[0..2]}-#
> >> {self.phone_before_type_cast[3..6]}" if !self.phone.nil? and
> >> self.phone_before_type_cast.length == 7
> >> self.phone = "(#{self.phone_before_type_cast[0..2]}) #
> >> {self.phone_before_type_cast[3..5]}-#{self.phone_before_type_cast
> >> [6..9]}" if !self.phone.nil? and self.phone_before_type_cast.length
> >> == 10
> >> end
> >
> > Sorry for my arrogance, but what an ugly code !
>
> If you can enlighten, how would you ?
Some ideas :
1/ Instead of 7 calls of #phone_before_type_cast, why not using
a variable ? tmp = self.phone_before_type_cast
2/ if self.phone is nil, in both cases you don't do anything, so you
can extract this condition.
unless self.phone.nil?
if ...
...
elsif ...
...
end
end
3/ then your conditions are very similar, they deal with tmp.length,
so you can use a case/when expressions.
case tmp.length
when 7
...
when 10
...
end
4/ According to your string manipulations, in fact you want to
insert hyphens in very specific positions. So one way is using
String#insert
So now you have many ways to make a cleaner and neater code !
-- Jean-François.
--
À la renverse.
More information about the Rails
mailing list