What would be the best way to define a method in the model that contains columns that can be nil, but are separated by a commas or hyphens if not nil? For example, a location where city and state will need to be followed by commas. This approach would obviously only work if city, state, and country were all required. Otherwise, I'm left with unwanted commas. For example, a user may have only a state listed or might have only a city and country.
User Model
def location
"#{city}, #{state}, #{country}"
end
I'm a try to avoid some really ugly code similar to what I've put below. Does anyone know of a cleaner or prettier way to write this?
Here's a bit of the ugly, bad approach I want to avoid. Basically, explicitly writing out each possibility.
def location
if !city.blank? && state.blank? && country.blank?
"#{city}, #{state}, #{country}"
end
end
Join the values that aren't blank:
def location
[city, state, country].reject(&:blank?).join(", ")
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.