Do rails have the opposite of “humanizing” for strings?

Rails adds the humanize() method for strings, which 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 a “pretty” input from the user I want to “de-humanize” to write to the model attribute:

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

Does the rails include any help for this?

Refresh

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?

Decision

Thank you, FD , for the link . I implemented the solution recommended there. In my config / initializers / .rb infection, 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 
+64
ruby-on-rails
May 14 '10 at 16:22
source share
3 answers

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 a shorter one (thanks @danielricecodes).

  • Rails <5 Employee salary".parameterize("_") # => employee_salary
  • Rails> 5 Employee salary".parameterize(separator: "_") # => employee_salary
+141
Apr 11 2018-11-11T00:
source share

There is no such method in the Rail API. However, I found this blog post that offers a (partial) solution: http://rubyglasses.blogspot.com/2009/04/dehumanizing-rails.html

+3
May 14 '10 at 16:33
source share

At http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html you have some methods used to prefix and delete strings.

+1
Jul 06 '11 at 16:16
source share



All Articles