Class: String

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

Overview

File: string.rb

Desc:  Monkey to the String class.

Instance Method Summary collapse

Instance Method Details

#to_camelcaseObject Also known as: camelcase, camelize

Convert camel_case to CamelCase



29
30
31
32
# File 'lib/patches/string.rb', line 29

def to_camelcase
  self.gsub(/\/(.?)/) { "::" + $1.upcase }
  		.gsub(/(^|_)(.)/) { $2.upcase }
end

#to_constantObject Also known as: constantize

Convert “CamelCase” into CamelCase



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/patches/string.rb', line 40

def to_constant
  names = self.split('::')
  names.shift if names.empty? || names.first.empty?

  constant = Object
  names.each do |name|
    if '1.9' == RUBY_VERSION[0,3]
      constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
    else
      constant = constant.const_get(name) || constant.const_missing(name)
    end
  end
  constant
end

#to_underscoreObject Also known as: to_snakecase, snakecase, snake_case, underscore

Convert CamelCase to camel_case



14
15
16
17
18
19
# File 'lib/patches/string.rb', line 14

def to_underscore
  self.gsub(/::/, '/')
  		.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
  		.gsub(/([a-z\d])([A-Z])/,'\1_\2').tr("- ", "_")
  		.downcase
end