Class: String

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

Direct Known Subclasses

YARD::Docstring

Instance Method Summary collapse

Instance Method Details

#camelcaseString

Camel cases any underscored text.

Examples:

"foo_bar_baz".camelcase # => "FooBarBaz"
"foo/bar".camelcase # => "Foo::Bar"

Returns:

  • the camel cased text



19
20
21
# File 'lib/yard/core_ext/string.rb', line 19

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

#shell_splitArray

Splits text into tokens the way a shell would, handling quoted text as a single token. Use ‘"’ and “'” to escape quotes and ‘\’ to escape a backslash.

Returns:

  • an array representing the tokens



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/yard/core_ext/string.rb', line 28

def shell_split
  out = [""]
  state = :none
  escape_next = false
  quote = ""
  strip.split(//).each do |char|
    case state
    when :none, :space
      case char
      when /\s/
        out << "" unless state == :space
        state = :space
        escape_next = false
      when "\\"
        if escape_next
          out.last << char
          escape_next = false
        else
          escape_next = true
        end
      when '"', "'"
        if escape_next
          out.last << char
          escape_next = false
        else
          state = char
          quote = ""
        end
      else
        state = :none
        out.last << char
        escape_next = false
      end
    when '"', "'"
      case char
      when '"', "'"
        if escape_next
          quote << char
          escape_next = false
        elsif char == state
          out.last << quote
          state = :none 
        else
          quote << char
        end
      when '\\'
        if escape_next
          quote << char
          escape_next = false
        else
          escape_next = true
        end
      else
        quote << char
        escape_next = false
      end
    end
  end
  out
end

#underscoreString

Separates capital letters following lower case letters by an underscore and returns the entire string in lower case

Examples:

"FooBar".underscore # => "foo_bar"
"Foo::Bar".underscore # => "foo/bar"

Returns:

  • the underscored lower case string



9
10
11
# File 'lib/yard/core_ext/string.rb', line 9

def underscore
  gsub(/([a-z])([A-Z])/, '\1_\2').downcase.gsub('::', '/')
end