Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 990
irkenInvader Avatar asked May 14 '10 16:05

irkenInvader


3 Answers

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
like image 121
giladbu Avatar answered Oct 19 '22 09:10

giladbu


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

like image 24
Mike Tunnicliffe Avatar answered Oct 19 '22 10:10

Mike Tunnicliffe


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

like image 2
fuzzyalej Avatar answered Oct 19 '22 11:10

fuzzyalej