Rails adds a humanize()
method for strings that works as follows (from the Rails RDoc):
"employee_salary".humanize # => "Employee salary"
"author_id".humanize # => "Author"
I want to go the other way. I have "pretty" input from a user that I want to 'de-humanize' for writing to a model's attribute:
"Employee salary" # => employee_salary
"Some Title: Sub-title" # => some_title_sub_title
Does rails include any help for this?
Update
In the meantime, I added the following to app/controllers/application_controller.rb:
class String
def dehumanize
self.downcase.squish.gsub( /\s/, '_' )
end
end
Is there a better place to put it?
Solution
Thanks, fd, for the link. I've implemented the solution recommended there. In my config/initializers/infections.rb, I added the following at the end:
module ActiveSupport::Inflector
# does the opposite of humanize ... mostly.
# Basically does a space-substituting .underscore
def dehumanize(the_string)
result = the_string.to_s.dup
result.downcase.gsub(/ +/,'_')
end
end
class String
def dehumanize
ActiveSupport::Inflector.dehumanize(self)
end
end