Module: ScoutAgent::CoreExtensions::String
- Defined in:
- lib/scout_agent/core_extensions.rb
Overview
Extensions for the String class.
Instance Method Summary collapse
-
#CamelCase ⇒ Object
(also: #camel_case)
Converts a String like “class_name” into “ClassName”.
-
#snake_case ⇒ Object
Converts a String like “ClassName” into “class_name”.
-
#to_question ⇒ Object
This helper swaps all trailing whitespace for two simple spaces.
-
#trim(width = self[/\A[ \t]*/].size) ⇒ Object
This helper will trim all lines in a String of leading whitespace.
-
#word_wrap(width = 60) ⇒ Object
Wraps a String to fit within the specified
width
, if possible.
Instance Method Details
#CamelCase ⇒ Object Also known as: camel_case
Converts a String like “class_name” into “ClassName”. Symbols and whitespace are removed.
209 210 211 212 213 |
# File 'lib/scout_agent/core_extensions.rb', line 209 def CamelCase tr("^A-Za-z0-9_", "_"). gsub(/(?:\A|_)([a-z])/) { $1.capitalize }. delete("_") end |
#snake_case ⇒ Object
Converts a String like “ClassName” into “class_name”. All runs of symbols and whitespace are replaced with a single “_”.
220 221 222 223 224 225 226 227 |
# File 'lib/scout_agent/core_extensions.rb', line 220 def snake_case tr("^A-Za-z0-9_", "_"). gsub(/(\D)(\d)/, "\\1_\\2"). gsub(/(\d)(\D)/, "\\1_\\2"). gsub(/([a-z])([A-Z])/, "\\1_\\2"). gsub(/_{2,}/, "_"). downcase end |
#to_question ⇒ Object
This helper swaps all trailing whitespace for two simple spaces. This is another method used to cleanup heredocs.
256 257 258 |
# File 'lib/scout_agent/core_extensions.rb', line 256 def to_question rstrip + " " end |
#trim(width = self[/\A[ \t]*/].size) ⇒ Object
This helper will trim all lines in a String of leading whitespace. By default, it trims the amount of space present on the first line, but you can override this by setting width
manually.
This method is handy for removing unwanted spacing in indented heredocs and thus helps keep the source clean:
def whatever
puts <<-END_MESSAGE.trim # clean up message
<- removes this space
<- and this
END_MESSAGE
end
248 249 250 |
# File 'lib/scout_agent/core_extensions.rb', line 248 def trim(width = self[/\A[ \t]*/].size) gsub(/^[ \t]{#{width}}/, "") end |
#word_wrap(width = 60) ⇒ Object
Wraps a String to fit within the specified width
, if possible. Newlines are inserted where spaces were, as needed.
264 265 266 267 268 269 |
# File 'lib/scout_agent/core_extensions.rb', line 264 def word_wrap(width = 60) strip. gsub(/\s+/, " "). gsub(/(.{1,#{width}}|\S{#{width + 1},})(?: +|$\n?)/, "\\1\n"). strip end |