lolthai
lolthai

Reputation: 59

Check for dash before applying titleize in Rails

I am really new to Ruby and Rails and need to know how to check if a string contains a dash before applying titlelize.

@city = City.first :conditions => { :title => params[:city].titleize }  

What I need to do is:

@city = City.first :conditions => { :title => params[:city] }

and then write something that will apply titleize ONLY if the @city variable doesn't contain a dash.

Upvotes: 4

Views: 799

Answers (2)

Piers C
Piers C

Reputation: 2978

I like 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

Upvotes: 3

Sully
Sully

Reputation: 14943

if params[:city] =~ /-/
  @city = City.first :conditions => { :title => params[:city] }
else
  @city = City.first :conditions => { :title => params[:city].titleize }     
end

I do not know why you are using this, but I believe it will not work for all cases. There should be a better approach.

Upvotes: 0

Related Questions