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 42 |
# File 'lib/redisabel/extensions/string.rb', line 39 def camelize return self.to_s.split(/_/).map(&:capitalize).join. split(/\//).map(&:capitalize).join('::') end |
#camelize! ⇒ Object
44 45 46 |
# File 'lib/redisabel/extensions/string.rb', line 44 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
48 49 50 51 |
# File 'lib/redisabel/extensions/string.rb', line 48 def underscore return self.to_s.sub(/:+/, '/').split(/([A-Z]?[^A-Z]*)/).reject(&:empty?). map(&:downcase).join('_').gsub(/\/_/, '/') end |
#underscore! ⇒ Object
53 54 55 |
# File 'lib/redisabel/extensions/string.rb', line 53 def underscore! self.replace(self.to_s.underscore) end |