简体   繁体   中英

Rails Address Format Helper

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
def delivery_address(customer)
  @customer =  Customer.find(customer.id)
  return "No Delivery Address" if @customer.del_address1.blank?

  [
    @customer.del_address1,
    @customer.del_address2,
    @customer.del_address3,
    @customer.del_address4,
    @customer.del_address5
  ].reject(&:blank?).join(",\n")
end

Rather than writing 5 if statements, you can put all values into an array, then delete any blank values.

Note that my code here is based on yours, but is not quite what your question asked for:

it will compact any nulls

An empty string is also considered blank? (but "" != nil ). So this method will also skip these values.

If you did only want to ignore nil values, but keep empty strings, then replace reject(&:blank?) with compact .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM