Module: Footing::String

Defined in:
lib/footing/extensions/string.rb

Instance Method Summary collapse

Instance Method Details

#boolean?Boolean

Indicates if this string represents a boolean value.

Returns:

  • (Boolean)


54
55
56
# File 'lib/footing/extensions/string.rb', line 54

def boolean?
  !!(self =~ /\A(true|false)\z/i)
end

#castObject

Casts this string to another datatype. Supported datatypes:

  • Integer

  • Float

  • Boolean



63
64
65
66
67
68
69
70
71
# File 'lib/footing/extensions/string.rb', line 63

def cast
  return to_f if numeric? && index(".")
  return to_i if numeric?
  if boolean?
    return true if self =~ /\Atrue\z/i
    return false if self =~ /\Afalse\z/i
  end
  self
end

#classifyObject



44
45
46
# File 'lib/footing/extensions/string.rb', line 44

def classify
  self.gsub(/\s/, "_").titleize.gsub(/\W/, "")
end

#escape(*chars) ⇒ Object

Escapes a series of chars.



26
27
28
29
30
# File 'lib/footing/extensions/string.rb', line 26

def escape(*chars)
  gsub(/(?<!\\)(#{chars.join("|")})/) do |char|
    "\\" + char
  end
end

#humanizeObject

Converts a word with underscores into a sentance with a capitalized first word.



33
34
35
# File 'lib/footing/extensions/string.rb', line 33

def humanize
  self.downcase.gsub(/_/, " ").capitalize
end

#numeric?Boolean

Indicates if this string represents a number.

Returns:

  • (Boolean)


49
50
51
# File 'lib/footing/extensions/string.rb', line 49

def numeric?
  !!(self =~ /\A[0-9]+\.*[0-9]*\z/)
end

#random(length = 12, opts = {}) ⇒ String

Generates a random string.

Examples:

Footing.util! Footing::String
Footing::String.random_key(100, :reject => ["1", "I", "l", "0", "O"])

Parameters:

  • length (Integer) (defaults to: 12)

    The length of the key to generate. Defaults to 12.

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :reject (Array)

    A list of characters to omit from the key.

  • :upcase (Boolean)

    Indicates that only use uppercase characters should be used.

Returns:



15
16
17
18
19
20
21
22
23
# File 'lib/footing/extensions/string.rb', line 15

def random(length=12, opts={})
  @chars ||= [(0..9).to_a, ('a'..'z').to_a, ('A'..'Z').to_a].flatten.map { |c| c.to_s }
  chars = @chars.reject do |c|
    c =~ /[a-z]/ if opts[:upcase]
  end
  opts[:reject] ||= []
  opts[:reject] = opts[:reject].map { |c| c.to_s }
  (1..length).map{ |i| (chars - opts[:reject]).sample }.join
end

#titleizeObject Also known as: titlecase

Similar to humanize but it capitalizes each word



38
39
40
# File 'lib/footing/extensions/string.rb', line 38

def titleize
  self.gsub(/\s/, "_").split('_').map(&:capitalize).join(' ')
end