Converting Camel Case to Underscore Case in Ruby

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"

Convert camelCase to dash-case (hypens) in pure ruby

ActiveRecord already has it:

gem install i18n activesupport-inflector

then

require 'active_support/inflector'
"myHTMLComponent".underscore.dasherize
# => "my-html-component"

You can see the implementation here (with acronym_underscore_regex here).

If you don't want to worry about corner cases like acronyms, this should suffice:

"myCamelCase".gsub(/[[:upper:]]/) { "-#{$&.downcase}" }
# => "my-camel-case"

Converting string from snake_case to CamelCase in Ruby

If you're using Rails, String#camelize is what you're looking for.

  "active_record".camelize                # => "ActiveRecord"
"active_record".camelize(:lower) # => "activeRecord"

If you want to get an actual class, you should use String#constantize on top of that.

"app_user".camelize.constantize

How do I convert a Ruby class name to a underscore-delimited symbol?

Rails comes with a method called underscore that will allow you to transform CamelCased strings into underscore_separated strings. So you might be able to do this:

FooBar.name.underscore.to_sym

But you will have to install ActiveSupport just to do that, as ipsum says.

If you don't want to install ActiveSupport just for that, you can monkey-patch underscore into String yourself (the underscore function is defined in ActiveSupport::Inflector):

class String
def underscore
word = self.dup
word.gsub!(/::/, '/')
word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
word.downcase!
word
end
end

Converting snake case to normal sentence in Ruby

humanize is your thing:

[4] pry(main)> "hello_world".humanize
"Hello world"

Ruby on Rails: Converting SomeWordHere to some word here

alt text

The methods underscore and humanize are designed for conversions between tables, class/package names, etc. You are better off using your own code to do the replacement to avoid surprises. See comments.

"SomeWordHere".underscore => "some_word_here"

"SomeWordHere".underscore.humanize => "Some word here"

"SomeWordHere".underscore.humanize.downcase => "some word here"

How to convert snake case to dash case in Rails

dasherize right there on the same page

"hello_world".dasherize # => 'hello-world'


Related Topics



Leave a reply



Submit