Strings passed will be formatted to obey English title rules.
"HAPPY BIRTHDAY".proper_titleize #=> Happy Birthday
"OvEr THE MouNTaiN And ThrOuGH thE WooDS".proper_titleize #=> Over the Mountain and Through the Woods
A link to the gist can be found below the source.
class String
# Converts a string into a properly capitalized English title
#
# @param [String] string the string to titleize
#
# @return [String] the titleized string
def proper_titleize
words = self.downcase.split(/\s+/)
combination_exceptions = [
'even though', 'so that', 'even if', # subordinating conjunctions
'to do', 'to be' # infinitives
]
exceptions = %w( because if after when although while since ) # subordinating conjunctions
exceptions += %w( the a an ) # articles
exceptions += %w( to do ) # infinitives
exceptions += %w( nor but or yet so both and either neither not
of in is for on with as by at from
amid anti as down into like minus near off
onto over past per plus save than up upon via ) # adposition
title = []
i = 0
while i < words.length do
if i == 0 or i == words.length-1 or words[i].upcase === words[i]
title.push(words[i].capitalize)
elsif combination_exceptions.include?("%s %s" % [words[i], words[i+1]])
title += [words[i], words[i+1]]
i += 1
elsif !exceptions.include?(words[i])
title.push(words[i].capitalize)
else
title.push(words[i])
end
i += 1
end
return title.join(' ').strip
end
end
(Source: gist.github.com)
In config/routes.rb if routes such as the following exist:
match "users/customers" => "users#customers", :as => :users_customers, :via => :get
match "users/employees" => "users#employees", :as => :users_employees, :via => :get
match "users/:id/toggle-status" => "users#toggle_status", :as => :users_toggle_status, :via => :put
the views associated with the :users_customers and :users_employees actions above (in this case each displaying a list-view of users of the specified type) likely both have a link referencing the :users_toggle_status route.
Within the toggle_status action the route to redirect back to can be determined by looking at the type of user who’s status is being toggled. A sample version of this action is below.
def toggle_status
user = User.find(params[:id])
user.toggle_status!
if user.type == 'employee'
redirect_to :users_employees and return
end
redirect_to :users_customers and return
end
The condition above and multiple redirect_to’s is cumbersome and unnecessary. Instead, we can use Ruby’s intern method for strings.
def toggle_status
user = User.find(params[:id])
user.toggle_status!
redirect_to ('users_%s' % user.type).intern and return
end