Class: String

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

Instance Method Summary collapse

Instance Method Details

#camel_caseString

Convert to camel case.

"foo_bar".camel_case          #=> "FooBar"

Returns:

  • (String)

    Receiver converted to camel case.



58
59
60
61
# File 'lib/rubyexts/string.rb', line 58

def camel_case
  return self if self !~ /_/ && self =~ /[A-Z]+.*/
  split('_').map{|e| e.capitalize}.join
end

#colorizeString

Transform self to ColoredString

Examples:

"message".colorize.red.bold

Parameters:

  • name (type)

    explanation

Returns:

  • (String)

    Transfrom self to ColoredString

Since:

  • 0.0.1



21
22
23
24
# File 'lib/rubyexts/string.rb', line 21

def colorize
  require_relative "colored_string"
  ColoredString.new(self)
end

#remove(pattern) ⇒ Object



26
27
28
# File 'lib/rubyexts/string.rb', line 26

def remove(pattern)
  self.gsub(pattern, "")
end

#remove!(pattern) ⇒ Object



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

def remove!(pattern)
  self.gsub!(pattern, "")
end

#snake_caseString

Convert to snake case.

"FooBar".snake_case           #=> "foo_bar"
"HeadlineCNNNews".snake_case  #=> "headline_cnn_news"
"CNN".snake_case              #=> "cnn"

Returns:

  • (String)

    Receiver converted to snake case.



44
45
46
47
48
# File 'lib/rubyexts/string.rb', line 44

def snake_case
  return self.downcase if self =~ /^[A-Z]+$/
  self.gsub(/([A-Z]+)(?=[A-Z][a-z]?)|\B[A-Z]/, '_\&') =~ /_*(.*)/
    return $+.downcase
end

#titlecaseString

Transform self into titlecased string.

Examples:

"hello world!".titlecase # => "Hello World!"

Returns:

  • (String)

    Titlecased string

Author:

  • Botanicus

Since:

  • 0.0.3



11
12
13
# File 'lib/rubyexts/string.rb', line 11

def titlecase
  self.gsub(/\b./) { $&.upcase }
end

#to_const_pathString

Convert a constant name to a path, assuming a conventional structure.

"FooBar::Baz".to_const_path # => "foo_bar/baz"

Returns:

  • (String)

    Path to the file containing the constant named by receiver (constantized string), assuming a conventional structure.



84
85
86
# File 'lib/rubyexts/string.rb', line 84

def to_const_path
  snake_case.gsub(/::/, "/")
end

#to_const_stringString

Convert a path string to a constant name.

"merb/core_ext/string".to_const_string #=> "Merb::CoreExt::String"

Returns:

  • (String)

    Receiver converted to a constant name.



71
72
73
# File 'lib/rubyexts/string.rb', line 71

def to_const_string
  gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
end