Module: Waves::Ext::String

Included in:
String
Defined in:
lib/waves/ext/string.rb

Overview

Utility methods mixed into String.

Instance Method Summary collapse

Instance Method Details

#/(s) ⇒ Object

Syntactic sugar for using File.join to concatenate the argument to the receiver.

require "lib" / "utilities" / "string"

The idea is not original, but we can’t remember where we first saw it. Waves::Ext::Symbol defines the same method, allowing for :files / ‘afilename.txt’



12
# File 'lib/waves/ext/string.rb', line 12

def / ( s ) ; File.join( self, s.to_s ); end

#basenameObject



34
# File 'lib/waves/ext/string.rb', line 34

def basename ; gsub(%r{^.*(::|/)}, '') ; end

#camelcase(style = :upper) ⇒ Object Also known as: camel_case



44
45
46
47
48
49
50
# File 'lib/waves/ext/string.rb', line 44

def camelcase( style = :upper )
  if style == :upper
    gsub( /_\w/ ) { |x| x[1,1].upcase }.gsub(/(^|\W)\w/) { |x| x.upcase }
  else
    gsub( /_\w/ ) { |x| x[1,1].upcase }.gsub(/(^|\W)\w/) { |x| x.downcase }
  end
end

#fqn2pathObject



33
# File 'lib/waves/ext/string.rb', line 33

def fqn2path ; gsub(/::/, '/') ; end

#in_wordsObject



35
# File 'lib/waves/ext/string.rb', line 35

def in_words ; gsub(%r{_|/|::}, ' ') ; end

#lowercaseObject Also known as: lower_case

Originally based on English gem. That code was (a) deprecated, (b) used confusing naming conventions (based on Rails original names, like ‘camelize’ instead of ‘camel_case’), and © was not thread-safe (making use of $ variables in gsub).

I have dispensed with things like “modulize” since (a) the meaning of that is sort of vague and (b) it is easy (and considerably clearer) to just use a method chain, like this: module.name.snake_case.fqn2path or (the reverse): path.camel_case.path2fqn



27
# File 'lib/waves/ext/string.rb', line 27

def lowercase ; downcase ; end

#ordinalObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/waves/ext/string.rb', line 53

def ordinal
  gsub(/\d+$/) { |x|
    x = x.to_i
    if (11..13).include?(x % 100)
      "#{i}th"
    else
      case x % 10
      when 1 then "#{x}st"
      when 2 then "#{x}nd"
      when 3 then "#{x}rd"
      else "#{x}th"
      end
    end
  }
end

#path2fqnObject



36
# File 'lib/waves/ext/string.rb', line 36

def path2fqn ; gsub(%r{/}, '::') ; end

#snakecaseObject Also known as: snake_case



38
39
40
41
# File 'lib/waves/ext/string.rb', line 38

def snakecase
  gsub( /(^|\W)[A-Z]/) { |x| x.downcase }.
  gsub(/[A-Z]/) { |x| "_#{x.downcase}" }
end

#titlecaseObject Also known as: title_case



31
# File 'lib/waves/ext/string.rb', line 31

def titlecase ; gsub( /\b\w/ ) { |x| x.upcase } ; end

#uppercaseObject Also known as: upper_case



29
# File 'lib/waves/ext/string.rb', line 29

def uppercase ; upcase ; end