Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/duffy/string.rb

Overview

Monkey Patch String adding useful methods.

Instance Method Summary collapse

Instance Method Details

#gender_humanObject



88
89
90
91
92
93
94
95
# File 'lib/duffy/string.rb', line 88

def gender_human
  case (self.to_s.upcase)
    when "M" then "Male"
    when "F" then "Female"
    when "O" then "Other"
    else ""
  end
end

#md5Object Also known as: md5sum

Easier way to calculate the md5sum of a string.



5
6
7
# File 'lib/duffy/string.rb', line 5

def md5
  Digest::MD5.hexdigest(self)
end

#nl2brObject



83
84
85
# File 'lib/duffy/string.rb', line 83

def nl2br
  (self.nil?)? "" : self.to_s.gsub(/(\r)?\n/, "<br />").html_safe
end

#pretty_committerObject

Parse a git username into a friendly name Expects committers to be a hash in this format: { jpd“ => ”Jacob“, /ers|Eric/ => ”Eric“ } All String keys are converted to Regex, explicit Regex is fine too.



74
75
76
# File 'lib/duffy/string.rb', line 74

def pretty_committer
  Hash(Duffy.configuration.committers).map{|k,v| v if Regexp.new(k) =~ self}.compact.first or self
end

#pretty_phoneObject



64
65
66
67
68
69
# File 'lib/duffy/string.rb', line 64

def pretty_phone
  number = self.to_s.gsub(/[^0-9\+]/, "")
  return "(" + number[0..2] + ") " + number[3..5] + "-" + number[6..9] if number.length == 10
  return number[0..2] + "-" + number[3..6] if number.length == 7
  number
end

#sanitize_ssnObject

Sanitize SSN.

“123456789” => “123456789” # Good “123-45-6789” => “123456789” # Good “000-12-3456” => nil # Invalid Area “666123456” => nil # Invalid Area “derp” => nil # Bogus “123456” => nil # Too short ( becomes 000123456: Invalid Area ) “999999999” => nil # Important. Many HRS entries “-” => nil # Important. Many HRS entries

www.ssa.gov/history/ssn/geocard.html en.wikipedia.org/wiki/Social_Security_number area: 001 to 665, 667 to 899 group: 01 to 99. serial: 0001 to 9999



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/duffy/string.rb', line 37

def sanitize_ssn
  begin
    ssn = "%09d" % self.to_numeric.to_i
    raise "Too Long" if ssn.length > 9
    area, group, serial = ssn[0..2], ssn[3..4], ssn[5..8]
    raise "Area Range Invalid" unless ("001" .. "665").cover?(area) or ("667" .. "899").cover?(area)
    raise "Group Range Invalid" unless ("01" .. "99").cover?(group)
    raise "Serial Range Invalid" unless ("0001" .. "9999").cover?(serial)
  rescue
    return nil
  end
  ssn
end

#smart_titlecaseObject

Smarter Titlecase function. Examples: “foo” => “Foo” “IMPORTANT STUFF” => “Important Stuff” “123 main st.” => “123 Main St.” “a tale of two cities” => “A Tale of Two Cities”



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/duffy/string.rb', line 104

def smart_titlecase
  small_re = %w( is a an and as at but by en for if in of on or the to v[.]? via vs[.]? ).join('|')

  # Original Perl version by: John Gruber        (daringfireball.net) 2008-05-10
  # Adapted to Ruby by:       Marshall Elfstrand (vengefulcow.com/    2008-05-21
  # Improved and customized:  Jacob Duffy        (duffy.jp)           2011-01-25
  # License:                  http://www.opensource.org/licenses/mit-license.php

  # if source is all uppercase, use all lowercase instead.  -- jpd
  string = (self.upcase == self)? self.downcase : self

  result = ""
  string.gsub(/[_-]/, ' ').split(/( [:.;?!][ ] | (?:[ ]|^)[""] )/x).each do |s|
    s.gsub!(/ \b( [[:alpha:]] [[:lower:].'']* )\b /x) do |w|
      # Skip words with inresult dots, e.g. "del.icio.us" or "example.com"
      (w =~ / [[:alpha:]] [.] [[:alpha:]] /x) ? w : w.capitalize
    end #gsub!

    # Lowercase our list of small words:
    s.gsub!(/\b(#{small_re})\b/io) { |w| w.downcase }

    # If the first word in the title is a small word, then capitalize it:
    s.gsub!(/\A([[:punct:]]*)(#{small_re})\b/io) { |w| $1 + $2.capitalize }

    # If the last word in the title is a small word, then capitalize it:
    s.gsub!(/\b(#{small_re})([[:punct:]]*)\Z/io) { |w| $1.capitalize + $2 }

    # Append current substring to output
    result += s
  end #each

  # Special Cases:
  upcase_re = (Array(Duffy.configuration.upcase_custom) + Array(Duffy.configuration.upcase_default)).uniq.join("|")

  result.gsub!(/ V(s?)\. /, ' v\1. ') # "v." and "vs."
  result.gsub!(/([''])S\b/, '\1s') # 'S (otherwise you get "the SEC'S decision")
  result.gsub!(/\b(#{upcase_re})\b/i) { |w| w.upcase } unless upcase_re.blank?
  result
end

#space2nbspObject



78
79
80
81
# File 'lib/duffy/string.rb', line 78

def space2nbsp
  # turns double space to double nbsp
  (self.nil?)? "" : self.to_s.gsub(/ {2}/, "&nbsp;&nbsp;").html_safe
end

#to_alphaObject



55
56
57
# File 'lib/duffy/string.rb', line 55

def to_alpha
  self.to_s.gsub(/[^a-zA-Z ]/, "").strip  # string with only a-z or A-Z or space, leading+trailing whitespace removed
end

#to_alpha_numericObject



59
60
61
# File 'lib/duffy/string.rb', line 59

def to_alpha_numeric
  self.to_s.gsub(/[^0-9a-zA-Z ]/, "").strip  # string with only a-z or A-Z or space, leading+trailing whitespace removed
end

#to_box(safe: true) ⇒ Object

Makes a nice box around your string for console output etc. See Array :to_box



12
13
14
# File 'lib/duffy/string.rb', line 12

def to_box(safe: true)
  Array(self).to_box(safe: safe) unless self.empty?
end

#to_numericObject



51
52
53
# File 'lib/duffy/string.rb', line 51

def to_numeric
  self.to_s.gsub(/[^0-9]/, "")            # now it's a string with only 0-9
end

#to_ssnObject



16
17
18
19
# File 'lib/duffy/string.rb', line 16

def to_ssn
  ssn = "%09d" % self.to_numeric.to_i           # strips string of non zeros, and pads leading zeros
  ssn[0..2] + "-" + ssn[3..4] + "-" + ssn[5..8] # now it's like 123-45-6789
end