Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/redisabel/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
- #camelize ⇒ Object
- #camelize! ⇒ Object
- #constantize ⇒ Object
- #underscore ⇒ Object
- #underscore! ⇒ Object
Instance Method Details
#camelize ⇒ Object
39 40 41 |
# File 'lib/redisabel/extensions/string.rb', line 39 def camelize return self.to_s.split(/_/).map(&:capitalize).join end |
#camelize! ⇒ Object
43 44 45 |
# File 'lib/redisabel/extensions/string.rb', line 43 def camelize! self.replace(self.to_s.camelize) end |
#constantize ⇒ Object
35 36 37 |
# File 'lib/redisabel/extensions/string.rb', line 35 def constantize return self.to_s.split('::').reduce(Module){ |m, c| m.const_get(c) } end |
#underscore ⇒ Object
47 48 49 50 |
# File 'lib/redisabel/extensions/string.rb', line 47 def underscore return self.to_s.split(/([A-Z]?[^A-Z]*)/).reject(&:empty?). map(&:downcase).join('_') end |
#underscore! ⇒ Object
52 53 54 |
# File 'lib/redisabel/extensions/string.rb', line 52 def underscore! self.replace(self.to_s.underscore) end |