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?
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?
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
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).
Employee salary".parameterize("_") # => employee_salary
Employee salary".parameterize(separator: "_") # => employee_salary
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
In http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html you have some methods used to prettify and un-prettify strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With