Module: Footing::String
- Defined in:
- lib/footing/extensions/string.rb
Instance Method Summary collapse
-
#boolean? ⇒ Boolean
Indicates if this string represents a boolean value.
-
#cast ⇒ Object
Casts this string to another datatype.
- #classify ⇒ Object
-
#escape(*chars) ⇒ Object
Escapes a series of chars.
-
#humanize ⇒ Object
Converts a word with underscores into a sentance with a capitalized first word.
-
#numeric? ⇒ Boolean
Indicates if this string represents a number.
-
#random(length = 12, opts = {}) ⇒ String
Generates a random string.
-
#titleize ⇒ Object
(also: #titlecase)
Similar to humanize but it capitalizes each word.
Instance Method Details
#boolean? ⇒ Boolean
Indicates if this string represents a boolean value.
54 55 56 |
# File 'lib/footing/extensions/string.rb', line 54 def boolean? !!(self =~ /\A(true|false)\z/i) end |
#cast ⇒ Object
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 |
#classify ⇒ Object
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 |
#humanize ⇒ Object
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.
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.
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 |
#titleize ⇒ Object 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 |