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/redisabel/extensions/string.rb, line 39 def camelize return self.to_s.split(/_/).map(&:capitalize).join. split(/\//).map(&:capitalize).join('::') end
camelize!()
click to toggle source
# File lib/redisabel/extensions/string.rb, line 44 def camelize! self.replace(self.to_s.camelize) end
constantize()
click to toggle source
# 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()
click to toggle source
# 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!()
click to toggle source
# File lib/redisabel/extensions/string.rb, line 53 def underscore! self.replace(self.to_s.underscore) end