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

Ruby on-Rails

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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 - Ruby on-Rails

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 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionirkenInvaderView Question on Stackoverflow
Solution 1 - Ruby on-RailsgiladbuView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMike TunnicliffeView Answer on Stackoverflow
Solution 3 - Ruby on-RailsfuzzyalejView Answer on Stackoverflow