I need a generic way to convert classnames to lowercase with underscores. For example, I wish to convert the classname NewUserBatch to new_user_batch. How to do this?
Underscore.
>> 'NewUserBatch'.underscore
=> "new_user_batch"
It is included in Rails so if you don't use it, you can refer to its source code.
def underscore(camel_cased_word)
word = camel_cased_word.to_s.dup
word.gsub!(%r::/, '/')
word.gsub!(%r(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
word.gsub!(%r([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(%r([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
word.downcase!
word
end
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