Using blank and compact in Ruby on Rails to help output incomplete data
Often I want to display a set of address fields, but only show the ones that have been filled in by the user.
For example if I have an Applicant with several address fields, then in the applicant model I will do the following:
def address
[address_1,
address_2,
address_3,
town,
county,
postcode].collect{|a| a unless a.blank? }.compact
end
The blank check makes the empty strings nil and the compact method removes the nil items. So you are left with only the fields with content output to the screen.
Then in the view I can do:
applicant.address.join("<br />")
Using the address method will output all the address fields the user has filled in, without me having to check each one individually if it has content.
The join method just put's <br />'s after each line as to create the following inside address tags:
<address>
25 The Street</br>
The City</br>
The County</br>
GU1 1AA
</address>
About
Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
2 comments made
I think you could accomplish the same thing in RoR with [....].select{ |a| a.blank? }
I think Mark means:
[....].reject{|a| a.blank?}
Got something to say?