Converting camel case to underscore case in ruby
Rails' ActiveSupport adds underscore to the String using the following:
class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
Then you can do fun stuff:
"CamelCase".underscore
=> "camel_case"
One-liner Ruby implementation:
class String
# ruby mutation methods have the expectation to return self if a mutation occurred, nil otherwise. (see http://www.ruby-doc.org/core-1.9.3/String.html#method-i-gsub-21)
def to_underscore!
gsub!(/(.)([A-Z])/,'\1_\2')
downcase!
end
def to_underscore
dup.tap { |s| s.to_underscore! }
end
end
So "SomeCamelCase".to_underscore # =>"some_camel_case"
You can use
"CamelCasedName".tableize.singularize
Or just
"CamelCasedName".underscore
Both options ways will yield "camel_cased_name"
. You can check more details it here.