Class: String

Inherits:
Object show all
Includes:
ActiveSupport::CoreExtensions::String::Access, ActiveSupport::CoreExtensions::String::Behavior, ActiveSupport::CoreExtensions::String::Conversions, ActiveSupport::CoreExtensions::String::Filters, ActiveSupport::CoreExtensions::String::Inflections, ActiveSupport::CoreExtensions::String::Iterators, ActiveSupport::CoreExtensions::String::Multibyte, ActiveSupport::CoreExtensions::String::StartsEndsWith, English::String, English::Style, English::Style::Replace, English::StyleORM, English::StyleORM::Replace
Defined in:
lib/gems/extlib-0.9.9/lib/extlib/blank.rb,
lib/mack-facets/extensions/string.rb,
lib/gems/extlib-0.9.9/lib/extlib/string.rb,
lib/gems/english-0.3.1/lib/english/roman.rb,
lib/gems/english-0.3.1/lib/english/style.rb,
lib/gems/english-0.3.1/lib/english/censor.rb,
lib/gems/english-0.3.1/lib/english/jumble.rb,
lib/gems/english-0.3.1/lib/english/string.rb,
lib/gems/english-0.3.1/lib/english/dresner.rb,
lib/gems/english-0.3.1/lib/english/inflect.rb,
lib/gems/english-0.3.1/lib/english/soundex.rb,
lib/gems/extlib-0.9.9/lib/extlib/inflection.rb,
lib/gems/english-0.3.1/lib/english/metaphone.rb,
lib/gems/english-0.3.1/lib/english/style_orm.rb,
lib/gems/english-0.3.1/lib/english/similarity.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/blank.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/string.rb,
lib/gems/activesupport-2.2.2/lib/active_support/json/encoders/string.rb,
lib/gems/activesupport-2.2.2/lib/active_support/vendor/builder-2.1.2/builder/xchar.rb,
lib/gems/activesupport-2.2.2/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb

Overview

Enhance the String class with a XML escaped character version of to_s.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ActiveSupport::CoreExtensions::String::Multibyte

#chars, #is_utf8?, #mb_chars

Methods included from ActiveSupport::CoreExtensions::String::Behavior

#acts_like_string?

Methods included from ActiveSupport::CoreExtensions::String::Iterators

append_features, #each_char

Methods included from ActiveSupport::CoreExtensions::String::StartsEndsWith

append_features, #ends_with?, #starts_with?

Methods included from ActiveSupport::CoreExtensions::String::Inflections

#camelize, #classify, #dasherize, #demodulize, #foreign_key, #parameterize, #tableize, #titleize, #underscore

Methods included from ActiveSupport::CoreExtensions::String::Filters

#squish, #squish!

Methods included from ActiveSupport::CoreExtensions::String::Conversions

#ord, #to_date, #to_datetime, #to_time

Methods included from ActiveSupport::CoreExtensions::String::Access

#at, #first, #from, #last, #to

Methods included from English::StyleORM::Replace

#camelize!, #classify!, #dasherize!, #foreign_key!, #humanize!, #tableize!, #titleize!, #underscore!

Methods included from English::StyleORM

#camelize, #classify, #dasherize, #foreign_key, #tableize, #titleize, #underscore

Methods included from English::String

#brief, #each_word_with_range, #fold, #word_wrap, #word_wrap!, #words

Methods included from English::Style::Replace

#camelcase!, #capitalcase!, #capitalize!, #demodulize!, #downcase!, #lowercase!, #methodize!, #modulize!, #ordinalize!, #pathize!, #snakecase!, #subcamelcase!, #titlecase!, #uncapitalcase!, #upcase!, #uppercase!

Methods included from English::Style

#camelcase, #capitalcase, #capitalize, #demodulize, #downcase, #lowercase, #modulize, #ordinalize, #pathize, #snakecase, #subcamelcase, #titlecase, #uncapitalize, #upcase, #uppercase

Class Method Details

.randomize(length = 10) ⇒ Object



116
117
118
119
120
121
# File 'lib/mack-facets/extensions/string.rb', line 116

def self.randomize(length = 10)
  chars = ("A".."H").to_a + ("J".."N").to_a + ("P".."T").to_a + ("W".."Z").to_a + ("3".."9").to_a
  newpass = ""
  1.upto(length) { |i| newpass << chars[rand(chars.size-1)] }
  return newpass.upcase
end

.translate(value) ⇒ Object

Overwrite this method to provide your own translations.



111
112
113
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 111

def self.translate(value)
  translations[value] || value
end

.translationsObject



115
116
117
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 115

def self.translations
  @translations ||= {}
end

Instance Method Details

#/(o) ⇒ String

Join with o as a file path.

"merb"/"core_ext" #=> "merb/core_ext"

Parameters:

  • o (String)

    Path component to join with receiver.

Returns:

  • (String)

    Receiver joined with o as a file path.



92
93
94
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 92

def /(other)
  File.join(self, other.to_s)
end

#blank?TrueClass, FalseClass

Strips out whitespace then tests if the string is empty.

"".blank?         #=>  true
"     ".blank?    #=>  true
" hey ho ".blank? #=>  false

Returns:



86
87
88
# File 'lib/gems/extlib-0.9.9/lib/extlib/blank.rb', line 86

def blank?
  strip.empty?
end

#camel_caseString

Convert to camel case.

"foo_bar".camel_case          #=> "FooBar"

Returns:

  • (String)

    Receiver converted to camel case.



52
53
54
55
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 52

def camel_case
  return self if self !~ /_/ && self =~ /[A-Z]+.*/
  split('_').map{|e| e.capitalize}.join
end

#censor(rules) ⇒ Object Also known as: rewrite

Apply a set of rules (regular expression matches) to the string.

The rules must be applied in order! So we cannot use a hash because the ordering is not guaranteed! we use an array instead.

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
# File 'lib/gems/english-0.3.1/lib/english/censor.rb', line 22

def censor(rules)
  raise ArgumentError.new('rules parameter is nil') unless rules  # gmosx: helps to find bugs
  s = dup
  rules.each do |match,edit|
    s.gsub!(match,edit)
  end
  return s
end

#censor_words(&blk) ⇒ Object Also known as: word_filter

Filters out words from a string based on block test.

"a string".word_filter { |word| word =~ /^a/ }  #=> "string"


47
48
49
50
# File 'lib/gems/english-0.3.1/lib/english/censor.rb', line 47

def censor_words( &blk )
  s = self.dup
  s.censor_words!( &blk )
end

#censor_words!Object Also known as: word_filter!

In place version of #word_filter.

"a string".word_filter { |word| ... }

TODO: Surely this can be written better.



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/gems/english-0.3.1/lib/english/censor.rb', line 60

def censor_words! #:yield:
  rest_of_string = self
  wordfind = /(\w+)/
  offset = 0
  while wmatch = wordfind.match(rest_of_string)
    word = wmatch[0]
    range = offset+wmatch.begin(0) ... offset+wmatch.end(0)
    rest_of_string = wmatch.post_match
    self[range] = yield( word ).to_s
    offset = self.length - rest_of_string.length
  end
  self
end

#censored?(rules) ⇒ Boolean

Make sure the string passes a collection of censorship rules defined with reqular expressions.

Returns:

  • (Boolean)


36
37
38
39
40
41
# File 'lib/gems/english-0.3.1/lib/english/censor.rb', line 36

def censored?(rules)
  for r in rules
    return true if self =~ r
  end
  return false
end

#compress_lines(spaced = true) ⇒ String

Replace sequences of whitespace (including newlines) with either a single space or remove them entirely (according to param spaced)

<<QUERY.compress_lines
  SELECT name
  FROM users
QUERY => "SELECT name FROM users"

Parameters:

  • spaced (TrueClass, FalseClass) (defaults to: true)

    (default=true) Determines whether returned string has whitespace collapsed or removed

Returns:

  • (String)

    Receiver with whitespace (including newlines) replaced



134
135
136
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 134

def compress_lines(spaced = true)
  split($/).map { |line| line.strip }.join(spaced ? ' ' : '')
end

#constantizeObject

Returns a constant of the string.

Examples:

"User".constantize # => User
"HomeController".constantize # => HomeController
"Mack::Configuration" # => Mack::Configuration


104
105
106
# File 'lib/mack-facets/extensions/string.rb', line 104

def constantize
  Module.instance_eval("::#{self}")
end

#crc32_ITU_TObject

Uses the ITU-T polynomial in the CRC32 algorithm.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/gems/activesupport-2.2.2/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb', line 40

def crc32_ITU_T
  n = length
  r = 0xFFFFFFFF

  n.times do |i|
    r ^= self[i]
    8.times do
      if (r & 1) != 0 then
        r = (r>>1) ^ 0xEDB88320
      else
        r >>= 1
      end
    end
  end

  r ^ 0xFFFFFFFF
end

#dresnerObject

Scramble the inner characters of words leaving the text still readable (research at Cambridge University, code by KurtDresner).

For example, the above text may result in:

Srblamce the iennr cchrteaars of wodrs lvenaig the txet stlil rbeaadle
(rreceash at Cbamigdre Uverintisy, cdoe by KrneruestDr?)


37
38
39
# File 'lib/gems/english-0.3.1/lib/english/dresner.rb', line 37

def dresner
  English::Dresner.dresner(self)
end

#dresner!Object

Inplace version of #dresner method.



43
44
45
# File 'lib/gems/english-0.3.1/lib/english/dresner.rb', line 43

def dresner!
  replace(dresner)
end

#each(&block) ⇒ Object



10
11
12
# File 'lib/mack-facets/extensions/string.rb', line 10

def each(&block)
  self.each_line(&block)
end

#escape_regexpString

Escape all regexp special characters.

"*?{}.".escape_regexp   #=> "\\*\\?\\{\\}\\."

Returns:

  • (String)

    Receiver with all regexp special characters escaped.



12
13
14
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 12

def escape_regexp
  Regexp.escape self
end

#hexdigestObject



108
109
110
# File 'lib/mack-facets/extensions/string.rb', line 108

def hexdigest
  Digest::SHA1.hexdigest(self)
end

#hexdigest!Object



112
113
114
# File 'lib/mack-facets/extensions/string.rb', line 112

def hexdigest!
  self.replace(self.hexdigest)
end

#humanizeObject

Capitalizes the first word and turns underscores into spaces and strips _id. Like titleize, this is meant for creating pretty output.

Examples

"employee_salary" #=> "Employee salary"
"author_id" #=> "Author"


94
95
96
# File 'lib/mack-facets/extensions/string.rb', line 94

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

#is_roman_numeral?Boolean

Returns true iif the subject is a roman numeral.

Returns:

  • (Boolean)


157
158
159
# File 'lib/gems/english-0.3.1/lib/english/roman.rb', line 157

def is_roman_numeral?
  English::RomanNumerals.is_roman_numeral?(self)
end

#jumbleObject

Jumble string.



27
28
29
# File 'lib/gems/english-0.3.1/lib/english/jumble.rb', line 27

def jumble
  English::Jumble.jumble(self)
end

#jumble!Object

In-place version of #jumble.



33
34
35
# File 'lib/gems/english-0.3.1/lib/english/jumble.rb', line 33

def jumble!
  replace(jumble)
end

#margin(indicator = nil) ⇒ String

Remove whitespace margin.

Parameters:

  • indicator (Object) (defaults to: nil)

    ???

Returns:

  • (String)

    receiver with whitespace margin removed



146
147
148
149
150
151
152
153
154
155
156
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 146

def margin(indicator = nil)
  lines = self.dup.split($/)

  min_margin = 0
  lines.each do |line|
    if line =~ /^(\s+)/ && (min_margin == 0 || $1.size < min_margin)
      min_margin = $1.size
    end
  end
  lines.map { |line| line.sub(/^\s{#{min_margin}}/, '') }.join($/)
end

#metaphoneObject

Returns the Metaphone representation of a string.



106
107
108
# File 'lib/gems/english-0.3.1/lib/english/metaphone.rb', line 106

def metaphone
  English::Metaphone.metaphone(self)
end

#methodizeObject

Raises:



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/mack-facets/extensions/string.rb', line 15

def methodize
  x = self
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  # get rid of the big stuff in the front/back
  x.strip!
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  x = x.underscore
  
  # get rid of spaces and make the _
  x.gsub!(' ', '_')
  # get rid of everything that isn't 'safe' a-z, 0-9, ?, !, =, _
  x.gsub!(/([^ a-zA-Z0-9\_\?\!\=]+)/n, '_')
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  # condense multiple 'safe' non a-z chars to just one.
  # ie. ___ becomes _ !!!! becomes ! etc...
  [' ', '_', '?', '!', "="].each do |c|
    x.squeeze!(c)
  end
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  #down case the whole thing
  x.downcase!
  
  # get rid of any characters at the beginning that aren't a-z
  while !x.match(/^[a-z]/)
    x.slice!(0)
    
    # if we get down to a nil or an empty string raise an exception! 
    raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  end
  
  # let's trim this bad boy down a bit now that we've cleaned it up, somewhat.
  # we should do this before cleaning up the end character, because it's possible to end up with a 
  # bad char at the end if you trim too late.
  x = x[0..100] if x.length > 100
  
  # get rid of any characters at the end that aren't safe
  while !x.match(/[a-z0-9\?\!\=]$/)
    x.slice!(x.length - 1)
    # if we get down to a nil or an empty string raise an exception! 
    raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  end
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  # let's get rid of characters that don't belong in the 'middle' of the method.
  orig_middle = x[1..(x.length - 2)]
  n_middle = orig_middle.dup
  
  ['?', '!', "="].each do |c|
    n_middle.gsub!(c, "_")
  end
  
  # the previous gsub can leave us with multiple underscores that need cleaning up.
  n_middle.squeeze!("_")
  
  x.gsub!(orig_middle, n_middle)
  x.gsub!("_=", "=")
  x
end

#pluralObject Also known as: pluralize



295
296
297
# File 'lib/gems/english-0.3.1/lib/english/inflect.rb', line 295

def plural
  English::Inflect.plural(self)
end

#relative_path_from(other) ⇒ String

Calculate a relative path from other.

"/opt/local/lib".relative_path_from("/opt/local/lib/ruby/site_ruby") # => "../.."

Parameters:

  • other (String)

    Base path to calculate from.

Returns:

  • (String)

    Relative path from other to receiver.



106
107
108
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 106

def relative_path_from(other)
  Pathname.new(self).relative_path_from(Pathname.new(other)).to_s
end

#similarity(str_in) ⇒ Object Also known as: fuzzy_match

A fuzzy matching mechanism. Returns a score from 0-1, based on the number of shared edges. To be effective, the strings must be of length 2 or greater.

"Alexsander".fuzzy_match( "Aleksander" )  #=> 0.9

The way it works:

  • Converts each string into a “graph like” object, with edges

    "alexsander" -> [ alexsander, alexsand, alexsan ... lexsand ... san ... an, etc ]
    "aleksander" -> [ aleksander, aleksand ... etc. ]
    
  • Perform match, then remove any subsets from this matched set (i.e. a hit on “san” is a subset of a hit on “sander”)

    Above example, once reduced -> [ ale, sander ]
    
  • See’s how many of the matches remain, and calculates a score based on how many matches, their length, and compare to the length of the larger of the two words.

– Credit goes to Derek Lewis. Thanks Derek! Still a bit rough. Any suggestions for improvement are welcome. ++



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/gems/english-0.3.1/lib/english/similarity.rb', line 41

def similarity( str_in )
  return 0 if str_in == nil
  return 1 if self == str_in

  # Make a graph of each word (okay, so its not a true graph, but is similar)
  graph_A = Array.new
  graph_B = Array.new

  # "graph" self
  last = self.length
  (0..last).each do |ff|
    loc  = self.length
    break if ff == last - 1
    wordB = (1..(last-1)).to_a.reverse!
    if (wordB != nil)
      wordB.each do |ss|
        break if ss == ff
        graph_A.push( "#{self[ff..ss]}" )
      end
    end
  end

  # "graph" input string
  last = str_in.length
  (0..last).each{ |ff|
    loc  = str_in.length
    break if ff == last - 1
    wordB = (1..(last-1)).to_a.reverse!
    wordB.each do |ss|
      break if ss == ff
      graph_B.push( "#{str_in[ff..ss]}" )
    end
  }

  # count how many of these "graph edges" we have that are the same
  matches = graph_A & graph_B
  #matches = Array.new
  #graph_A.each do |aa|
  #  matches.push( aa ) if( graph_B.include?( aa ) )
  #end

  # For eliminating subsets, we want to start with the smallest hits.
  matches.sort!{|x,y| x.length <=> y.length}

  # eliminate any subsets
  mclone = matches.dup
  mclone.each_index do |ii|
    reg = Regexp.compile( Regexp.escape(mclone[ii]) )
    count = 0.0
    matches.each{|xx| count += 1 if xx =~ reg}
    matches.delete(mclone[ii]) if count > 1
  end

  score = 0.0
  matches.each{ |mm| score += mm.length }
  self.length > str_in.length ? largest = self.length : largest = str_in.length
  return score/largest
end

#singularObject Also known as: singularize



290
291
292
# File 'lib/gems/english-0.3.1/lib/english/inflect.rb', line 290

def singular
  English::Inflect.singular(self)
end

#snake_caseString

Convert to snake case.

"FooBar".snake_case           #=> "foo_bar"
"HeadlineCNNNews".snake_case  #=> "headline_cnn_news"
"CNN".snake_case              #=> "cnn"

Returns:

  • (String)

    Receiver converted to snake case.



38
39
40
41
42
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 38

def snake_case
  return self.downcase if self =~ /^[A-Z]+$/
  self.gsub(/([A-Z]+)(?=[A-Z][a-z]?)|\B[A-Z]/, '_\&') =~ /_*(.*)/
    return $+.downcase
end

#soundexObject



66
67
68
# File 'lib/gems/english-0.3.1/lib/english/soundex.rb', line 66

def soundex
  English::Soundex.soundex(self)
end

#t(*values) ⇒ String

Formats String for easy translation. Replaces an arbitrary number of values using numeric identifier replacement.

"%s %s %s" % %w(one two three)        #=> "one two three"
"%3$s %2$s %1$s" % %w(one two three)  #=> "three two one"

Parameters:

  • values (#to_s)

    A list of values to translate and interpolate into receiver

Returns:

  • (String)

    Receiver translated with values translated and interpolated positionally



172
173
174
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 172

def t(*values)
  self.class::translate(self) % values.collect! { |value| value.frozen? ? value : self.class::translate(value.to_s) }
end

#to_const_pathString

Convert a constant name to a path, assuming a conventional structure.

"FooBar::Baz".to_const_path # => "foo_bar/baz"

Returns:

  • (String)

    Path to the file containing the constant named by receiver (constantized string), assuming a conventional structure.



78
79
80
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 78

def to_const_path
  snake_case.gsub(/::/, "/")
end

#to_const_stringString

Convert a path string to a constant name.

"merb/core_ext/string".to_const_string #=> "Merb::CoreExt::String"

Returns:

  • (String)

    Receiver converted to a constant name.



65
66
67
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 65

def to_const_string
  gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
end

#to_i_romanObject

Considers string a roman numeral numeral, and converts it to the corresponding integer.



151
152
153
# File 'lib/gems/english-0.3.1/lib/english/roman.rb', line 151

def to_i_roman
  English::RomanNumerals.to_integer(self)
end

#to_json(options = nil) ⇒ Object

:nodoc:



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/gems/activesupport-2.2.2/lib/active_support/json/encoders/string.rb', line 25

def to_json(options = nil) #:nodoc:
  json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s|
    ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s]
  }
  json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
  json.gsub(/([\xC0-\xDF][\x80-\xBF]|
           [\xE0-\xEF][\x80-\xBF]{2}|
           [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
    s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&')
  } + '"'
end

#to_xsObject

XML escaped version of to_s



110
111
112
113
114
# File 'lib/gems/activesupport-2.2.2/lib/active_support/vendor/builder-2.1.2/builder/xchar.rb', line 110

def to_xs
  unpack('U*').map {|n| n.xchr}.join # ASCII, UTF-8
rescue
  unpack('C*').map {|n| n.xchr}.join # ISO-8859-1, WIN-1252
end

#truncate(length = 30, truncate_string = "...") ⇒ Object



139
140
141
142
143
144
145
146
147
148
# File 'lib/mack-facets/extensions/string.rb', line 139

def truncate(length = 30, truncate_string = "...")
  if self.nil? then return end
  l = length - truncate_string.length
  if $KCODE == "NONE"
    self.length > length ? self[0...l] + truncate_string : self
  else
    chars = self.split(//)
    chars.length > length ? chars[0...l].join + truncate_string : self
  end
end

#truncate!(length = 30, truncate_string = "...") ⇒ Object



150
151
152
# File 'lib/mack-facets/extensions/string.rb', line 150

def truncate!(length = 30, truncate_string = "...")
  self.replace(self.truncate(length, truncate_string))
end

#unescape_regexpString

Unescape all regexp special characters.

"\\*\\?\\{\\}\\.".unescape_regexp #=> "*?{}."

Returns:

  • (String)

    Receiver with all regexp special characters unescaped.



24
25
26
# File 'lib/gems/extlib-0.9.9/lib/extlib/string.rb', line 24

def unescape_regexp
  self.gsub(/\\([\.\?\|\(\)\[\]\{\}\^\$\*\+\-])/, '\1')
end

#uri_escapeObject

Performs URI escaping so that you can construct proper query strings faster. Use this rather than the cgi.rb version since it’s faster. (Stolen from Camping).



126
127
128
129
130
# File 'lib/mack-facets/extensions/string.rb', line 126

def uri_escape
  self.gsub(/([^ a-zA-Z0-9_.-]+)/n) {
    '%'+$1.unpack('H2'*$1.size).join('%').upcase
  }.tr(' ', '+')
end

#uri_unescapeObject

Unescapes a URI escaped string. (Stolen from Camping).



133
134
135
136
137
# File 'lib/mack-facets/extensions/string.rb', line 133

def uri_unescape
  self.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){
    [$1.delete('%')].pack('H*')
  }
end