Check the dash before applying the title in Rails
I'm really new to Ruby and Rails and should know how to check if a string contains a dash before applying titlelize.
@city = City.first :conditions => { :title => params[:city].titleize }
What do I need to do:
@city = City.first :conditions => { :title => params[:city] }
and then write something that will use titleize ONLY if the variable @city
does not contain a dash.
+3
source to share
2 answers
I love this solution, added by zachrose a couple of weeks ago: https://gist.github.com/varyonic/ccda540c417a6bd49aec
def nice_title(phrase)
return phrase if phrase =~ /^-+$/
phrase.split('-').map { |part|
if part.chars.count == part.bytes.count
part.titleize
else
part.split(' ').map { |word| word.mb_chars.titleize }.join(' ')
end
}.join('-')
end
+3
source to share