Within the last few days I saw an excellent example of this but can’t
find the link. So… I thought I’d ask the experts.
In my addressbook model, I wanted to be able to just say
thing.full_address to return a preformatted version of the customers
entire address. Something like this:
from addressbook model
def full_address
full = first_name + ’ ’ + last_name + ‘
’ + address1 + ‘
’
unless address2.blank?; full += address2 + “
”; end
full += city + ’ ’ + state + ‘,’ + zip
full
end
I’m sure there’s a cleaner more compact way to do this, but this is the
extent of my ruby knowledge at this point.
Any help cleaning / compacting this would be greatly appriciated.
Thanks!
On Aug 22, 2006, at 5:52 PM, David C. wrote:
unless address2.blank?; full += address2 + “
”; end
full += city + ’ ’ + state + ‘,’ + zip
full
end
I’m sure there’s a cleaner more compact way to do this, but this is
the
extent of my ruby knowledge at this point.
Any help cleaning / compacting this would be greatly appriciated.
Don’t put view code (HTML) in your models!
Better to put that in a helper.
–
– Tom M.
Tom M. wrote:
def full_address
Any help cleaning / compacting this would be greatly appriciated.
Don’t put view code (HTML) in your models!
Better to put that in a helper.
–
– Tom M.
I’m with Tom on this one.
Make a partial that properly formats the address when passed the
object.
FWIW, the format I think you were looking for is like this…
def print_stuff
“#{variable1}-#{variable2}”
end
_Kevin
www.sciwerks.com
On 8/23/06, David C. [email protected] wrote:
from addressbook model
Any help cleaning / compacting this would be greatly appriciated.
Thanks!
One thing I’d suggest is writing a function in the model like this:
def full_address
[first_name + ’ ’ + last_name,
address1,
address2,
city + ’ ’ + state + ‘,’ + zip].compact # compact removes nil
values from an array
end
and then a helper
def format_address(object)
object.respond_to?(“full_address”) and
object.full_address.join(“
”)
end
Gareth
FYI, Added the delete_if to get rid of the blank ones:
def full_address
addr = [first_name + ’ ’ + last_name,
address1,
address2,
city + ’ ’ + state + ', ’ + zip].compact
addr.delete_if {|x| x.blank? }
end
thx.
Gareth A. wrote:
def full_address
[first_name + ’ ’ + last_name,
address1,
address2,
city + ’ ’ + state + ‘,’ + zip].compact # compact removes nil
values from an array
end
Almost worked. address2.nil? returns false, but address2.blank? returns
true. Since address2 isn’t nil, it still shows.
Thanks for pointing me in the right direction!!