I am trying to create a helper that will format an address from 5 columns (add1,add2, add3,add4,add5) so that it will compact any nulls and display on screen as such
Add1,
Add3,
Add4,
Add5
(add 2 was skipped as it was null)
I created the following helper to assemble and skip any nulls but I can not introduce a new line break. Any ideas?
def delivery_address(customer)
@customer = Customer.find(customer.id)
if @customer.del_address1.blank?
deladdress = "No Delivery Address"
else
deladdress = @customer.del_address1
deladdress = deladdress + "</br>"
if customer.del_address2.blank?
else
deladdress = deladdress + @customer.del_address2 + ","
end
if @customer.del_address3.blank?
else
deladdress = deladdress + @customer.del_address3 + ","
end
if @customer.del_address4.blank?
else
deladdress = deladdress + @customer.del_address4 + ","
end
if @customer.del_address5.blank?
else
deladdress = deladdress + @customer.del_address5
end
end
end
One important advise: You should not do any database queries inside a view helper. This should only be done in the controller. An active record should already be passed into the helper function. So this line
@customer = Customer.find(customer.id)
can be removed.
def delivery_address(customer)
# Use a guard clause, this reduces if nesting
return 'No Delivery Address' if customer.del_address1.blank?
# Collect all parts
parts = [customer.del_address1, customer.del_address2, customer.del_address3, customer.del_address4, customer.del_address5]
# Remove all empty parts.
# Using a bang method is lighter on memory allocation
# and will speed up performance.
parts.reject!(&:blank?)
parts.join('<br/>').html_safe
end