class String

String class extension

A string that is supposed to becode a Module, Class or similar can be transformed by using constantize

"Array".constantize
=> Array

When writing file names in ruby, they are usually an underscore (snakecase) representation of the class name. It can be transformed with camelize and in place with camelize!

"file_reader".camelize
=> "FileReader"

s = "file_reader"
s.camelize!
s
=> "FileReader"

The backwards transformation from a class name to snakecase is done with underscore and in place with underscore!

"FileReader".underscore
=> "file_reader"

s = "FileReader".underscore
s.underscore!
s
=> "file_reader"

Public Instance Methods

camelize() click to toggle source
# File lib/cargobull/extensions/string.rb, line 47
def camelize
  split(/_/).map(&:capitalize).join.path_to_modules
end
camelize!() click to toggle source
# File lib/cargobull/extensions/string.rb, line 51
def camelize!
  replace(camelize)
end
constantize() click to toggle source
# File lib/cargobull/extensions/string.rb, line 35
def constantize
  split('::').reduce(Module){ |m, c| m.const_get(c) }
end
modules_to_path() click to toggle source
# File lib/cargobull/extensions/string.rb, line 43
def modules_to_path
  sub(/:+/, '/')
end
path_to_modules() click to toggle source
# File lib/cargobull/extensions/string.rb, line 39
def path_to_modules
  split(/\//).map(&:capitalize).join('::')
end
underscore() click to toggle source
# File lib/cargobull/extensions/string.rb, line 55
def underscore
  modules_to_path.split(/([A-Z]?[^A-Z]*)/).reject(&:empty?).
    map(&:downcase).join('_').gsub(/\/_/, '/')
end
underscore!() click to toggle source
# File lib/cargobull/extensions/string.rb, line 60
def underscore!
  replace(underscore)
end