Does rails have an opposite of 'humanize' for strings?

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

Solution 1:

the string.parameterize.underscore will give you the same result

"Employee salary".parameterize.underscore       # => employee_salary
"Some Title: Sub-title".parameterize.underscore # => some_title_sub_title

or you can also use which is slightly more succinct (thanks @danielricecodes).

  • Rails < 5 Employee salary".parameterize("_") # => employee_salary
  • Rails > 5 Employee salary".parameterize(separator: "_") # => employee_salary

Solution 2:

There doesn't appear to be any such method in the Rail API. However, I did find this blog post that offers a (partial) solution: http://rubyglasses.blogspot.com/2009/04/dehumanizing-rails.html

Solution 3:

In http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html you have some methods used to prettify and un-prettify strings.