Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/cargobull/extensions/string.rb

Overview

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"

Instance Method Summary collapse

Instance Method Details

#camelizeObject



47
48
49
# File 'lib/cargobull/extensions/string.rb', line 47

def camelize
  split(/_/).map(&:capitalize).join.path_to_modules
end

#camelize!Object



51
52
53
# File 'lib/cargobull/extensions/string.rb', line 51

def camelize!
  replace(camelize)
end

#constantizeObject



35
36
37
# File 'lib/cargobull/extensions/string.rb', line 35

def constantize
  split('::').reduce(Module){ |m, c| m.const_get(c) }
end

#modules_to_pathObject



43
44
45
# File 'lib/cargobull/extensions/string.rb', line 43

def modules_to_path
  sub(/:+/, '/')
end

#path_to_modulesObject



39
40
41
# File 'lib/cargobull/extensions/string.rb', line 39

def path_to_modules
  split(/\//).map(&:capitalize).join('::')
end

#underscoreObject



55
56
57
58
# 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!Object



60
61
62
# File 'lib/cargobull/extensions/string.rb', line 60

def underscore!
  replace(underscore)
end