Class: Lotus::Utils::String

Inherits:
String
  • Object
show all
Defined in:
lib/lotus/utils/string.rb

Overview

String on steroids

Since:

  • 0.1.0

Constant Summary collapse

NAMESPACE_SEPARATOR =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Separator between Ruby namespaces

Examples:

Lotus::Utils

Since:

  • 0.1.0

'::'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ String

Initialize the string

Parameters:

  • string (::String, Symbol)

    the value we want to initialize

Since:

  • 0.1.0



23
24
25
# File 'lib/lotus/utils/string.rb', line 23

def initialize(string)
  super(string.to_s)
end

Instance Method Details

#classifyString

Return a CamelCase version of the string

Examples:

require 'lotus/utils/string'

string = Lotus::Utils::String.new 'lotus_utils'
string.classify # => 'LotusUtils'

Returns:

  • (String)

    the transformed string

Since:

  • 0.1.0



38
39
40
# File 'lib/lotus/utils/string.rb', line 38

def classify
  split('_').map {|token| token.slice(0).upcase + token.slice(1..-1) }.join
end

#demodulizeString

Return the string without the Ruby namespace of the class

Examples:

require 'lotus/utils/string'

string = Lotus::Utils::String.new 'Lotus::Utils::String'
string.demodulize # => 'String'

string = Lotus::Utils::String.new 'String'
string.demodulize # => 'String'

Returns:

  • (String)

    the transformed string

Since:

  • 0.1.0



77
78
79
# File 'lib/lotus/utils/string.rb', line 77

def demodulize
  split(NAMESPACE_SEPARATOR).last
end

#tokenize(&blk) ⇒ void

This method returns an undefined value.

It iterates thru the tokens and calls the given block. A token is a substring wrapped by ‘()` and separated by `|`.

Examples:

require 'lotus/utils/string'

string = Lotus::Utils::String.new 'Lotus::(Utils|App)'
string.tokenize do |token|
  puts token
end

# =>
  'Lotus::Utils'
  'Lotus::App'

Parameters:

  • blk (Proc, #call)

    the block that is called for each token.

Since:

  • 0.1.0



101
102
103
104
105
106
107
108
109
110
# File 'lib/lotus/utils/string.rb', line 101

def tokenize(&blk)
  template = gsub(/\((.*)\)/, "%{token}")
  tokens   = Array(( $1 || self ).split('|'))

  tokens.each do |token|
    blk.call(template % {token: token})
  end

  nil
end

#underscoreString

Return a downcased and underscore separated version of the string

Revised version of ‘ActiveSupport::Inflector.underscore` implementation

Examples:

require 'lotus/utils/string'

string = Lotus::Utils::String.new 'LotusUtils'
string.underscore # => 'lotus_utils'

Returns:

  • (String)

    the transformed string

See Also:

Since:

  • 0.1.0



56
57
58
59
60
61
# File 'lib/lotus/utils/string.rb', line 56

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