Class: String

Inherits:
Object show all
Defined in:
lib/backports/rails/string.rb,
lib/backports/1.9.1/string/chr.rb,
lib/backports/1.9.1/string/ord.rb,
lib/backports/1.8.7/string/upto.rb,
lib/backports/1.9.1/string/clear.rb,
lib/backports/2.3.0/string/uplus.rb,
lib/backports/2.4.0/string/match.rb,
lib/backports/2.3.0/string/uminus.rb,
lib/backports/2.5.0/string/undump.rb,
lib/backports/force/string_length.rb,
lib/backports/1.9.3/string/prepend.rb,
lib/backports/2.4.0/string/unpack1.rb,
lib/backports/1.8.7/string/end_with.rb,
lib/backports/1.8.7/string/each_char.rb,
lib/backports/1.8.7/string/partition.rb,
lib/backports/1.9.3/string/byteslice.rb,
lib/backports/1.8.7/string/rpartition.rb,
lib/backports/1.8.7/string/start_with.rb,
lib/backports/1.9.1/string/ascii_only.rb,
lib/backports/1.9.1/string/codepoints.rb,
lib/backports/2.5.0/string/delete_prefix.rb,
lib/backports/2.5.0/string/delete_prefix.rb,
lib/backports/2.5.0/string/delete_suffix.rb,
lib/backports/2.5.0/string/delete_suffix.rb,
lib/backports/2.2.0/string/unicode_normalize.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.try_convert(x) ⇒ Object



4
5
6
# File 'lib/backports/1.9.1/string/try_convert.rb', line 4

def String.try_convert(x)
  Backports.try_convert(x, String, :to_str)
end

Instance Method Details

#+@Object



3
4
5
# File 'lib/backports/2.3.0/string/uplus.rb', line 3

def +@
  frozen? ? dup : self
end

#-@Object



3
4
5
# File 'lib/backports/2.3.0/string/uminus.rb', line 3

def -@
  frozen? ? self : dup.freeze
end

#ascii_only?Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/backports/1.9.1/string/ascii_only.rb', line 3

def ascii_only?
  !(self =~ /[^\x00-\x7f]/)
end

#byteslice(start, len = Backports::Undefined) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/backports/1.9.3/string/byteslice.rb', line 5

def byteslice(start, len = Backports::Undefined)
  # Argument parsing & checking
  if Backports::Undefined == len
    if start.is_a?(Range)
      range = start
      start = Backports.coerce_to_int(range.begin)
      start += bytesize if start < 0
      last = Backports.coerce_to_int(range.end)
      last += bytesize if last < 0
      last += 1 unless range.exclude_end?
      len = last - start
    else
      start = Backports.coerce_to_int(start)
      start += bytesize if start < 0
      len = 1
      return if start >= bytesize
    end
  else
    start = Backports.coerce_to_int(start)
    start += bytesize if start < 0
    len = Backports.coerce_to_int(len)
    return if len < 0
  end
  return if start < 0 || start > bytesize
  len = 0 if len < 0
  # Actual implementation:
  str = unpack("@#{start}a#{len}").first
  str = dup.replace(str) unless self.instance_of?(String) # Must return subclass
  str.force_encoding(encoding) if respond_to?(:encoding)
  str
end

#camelize(first_letter = :upper) ⇒ Object

Standard in rails. See official documentation



7
8
9
10
11
12
13
# File 'lib/backports/rails/string.rb', line 7

def camelize(first_letter = :upper)
  if first_letter == :upper
    gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
  else
    self[0..0].downcase + camelize[1..-1]
  end
end

#chrObject



3
4
5
# File 'lib/backports/1.9.1/string/chr.rb', line 3

def chr
  chars.first || ""
end

#clearObject



3
4
5
6
# File 'lib/backports/1.9.1/string/clear.rb', line 3

def clear
  self[0,length] = ""
  self
end

#codepointsObject



3
4
5
6
7
# File 'lib/backports/1.9.1/string/codepoints.rb', line 3

def codepoints
  return to_enum(:codepoints) unless block_given?
  unpack("U*").each{|cp| yield cp}
  self
end

#constantizeObject

Standard in rails. See official documentation



16
17
18
19
20
21
22
23
24
25
# File 'lib/backports/rails/string.rb', line 16

def constantize
  names = split('::')
  names.shift if names.empty? || names.first.empty?

  constant = Object
  names.each do |name|
    constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
  end
  constant
end

#dasherizeObject

Standard in rails. See official documentation



28
29
30
# File 'lib/backports/rails/string.rb', line 28

def dasherize
  gsub(/_/, '-')
end

#delete_prefix(prefix) ⇒ Object



5
6
7
8
9
10
11
12
# File 'lib/backports/2.5.0/string/delete_prefix.rb', line 5

def delete_prefix(prefix)
  prefix = Backports.coerce_to_str(prefix)
  if rindex(prefix, 0)
    self[prefix.length..-1]
  else
    dup
  end
end

#delete_prefix!(prefix) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/backports/2.5.0/string/delete_prefix.rb', line 20

def delete_prefix!(prefix)
  prefix = Backports.coerce_to_str(prefix)
  chomp! if frozen?
  len = prefix.length
  if len > 0 && rindex(prefix, 0)
    self[0...prefix.length] = ''
    self
  else
    nil
  end
end

#delete_suffix(suffix) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/backports/2.5.0/string/delete_suffix.rb', line 5

def delete_suffix(suffix)
  suffix = Backports.coerce_to_str(suffix)
  len = suffix.length
  if len > 0 && index(suffix, -len)
    self[0...-len]
  else
    dup
  end
end

#delete_suffix!(suffix) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/backports/2.5.0/string/delete_suffix.rb', line 21

def delete_suffix!(suffix)
  suffix = Backports.coerce_to_str(suffix)
  chomp! if frozen?
  len = suffix.length
  if len > 0 && index(suffix, -len)
    self[-len..-1] = ''
    self
  else
    nil
  end
end

#demodulizeObject

Standard in rails. See official documentation



33
34
35
# File 'lib/backports/rails/string.rb', line 33

def demodulize
  gsub(/^.*::/, '')
end

#each_charObject Also known as: chars



6
7
8
9
# File 'lib/backports/1.8.7/string/each_char.rb', line 6

def each_char
  return to_enum(:each_char) unless block_given?
  scan(/./m) {|c| yield c}
end

#end_with?(*suffixes) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
# File 'lib/backports/1.8.7/string/end_with.rb', line 3

def end_with?(*suffixes)
  suffixes.any? do |suffix|
    if suffix.respond_to? :to_str
      suffix = suffix.to_str
      self[-suffix.length, suffix.length] == suffix
    end
  end
end

#lengthObject Also known as: size



5
6
7
# File 'lib/backports/force/string_length.rb', line 5

def length
  unpack("U*").length
end

#match?(*args) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/backports/2.4.0/string/match.rb', line 3

def match?(*args)
  !match(*args).nil?
end

#ordObject



3
4
5
# File 'lib/backports/1.9.1/string/ord.rb', line 3

def ord
  codepoints.first or raise ArgumentError, "empty string"
end

#partition_with_new_meaning(pattern = Backports::Undefined) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/backports/1.8.7/string/partition.rb', line 6

def partition_with_new_meaning(pattern = Backports::Undefined)
  return partition_without_new_meaning{|c| yield c} if pattern == Backports::Undefined
  pattern = Backports.coerce_to(pattern, String, :to_str) unless pattern.is_a? Regexp
  i = index(pattern)
  return [self, "", ""] unless i
  if pattern.is_a? Regexp
    match = Regexp.last_match
    [match.pre_match, match[0], match.post_match]
  else
    last = i+pattern.length
    [self[0...i], self[i...last], self[last...length]]
  end
end

#prepend(other_str) ⇒ Object



5
6
7
8
# File 'lib/backports/1.9.3/string/prepend.rb', line 5

def prepend(other_str)
  replace Backports.coerce_to_str(other_str) + self
  self
end

#rpartition(pattern) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/backports/1.8.7/string/rpartition.rb', line 5

def rpartition(pattern)
  pattern = Backports.coerce_to(pattern, String, :to_str) unless pattern.is_a? Regexp
  i = rindex(pattern)
  return ["", "", self] unless i

  if pattern.is_a? Regexp
    match = Regexp.last_match
    [match.pre_match, match[0], match.post_match]
  else
    last = i+pattern.length
    [self[0...i], self[i...last], self[last...length]]
  end
end

#start_with?(*prefixes) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
# File 'lib/backports/1.8.7/string/start_with.rb', line 3

def start_with?(*prefixes)
  prefixes.any? do |prefix|
    if prefix.respond_to? :to_str
      prefix = prefix.to_str
      self[0, prefix.length] == prefix
    end
  end
end

#underscoreObject

Standard in rails. See official documentation



38
39
40
41
42
43
44
# File 'lib/backports/rails/string.rb', line 38

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

#undumpObject



3
4
5
6
7
8
9
10
11
12
13
14
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
# File 'lib/backports/2.5.0/string/undump.rb', line 3

def undump
  # Making sure to return a String and not a subclass
  string = to_s
  raise 'string contains null byte' if string["\0"]
  raise 'non-ASCII character detected' unless string.ascii_only?

  match = string.match(/\A(".*?"?)(?:\.force_encoding\("([^"]*)"\))?\z/) or
    raise %(invalid dumped string; not wrapped with '"' nor '"...".force_encoding("...")' form)
  string = match[1]
  encoding = match[2]

  # Ruby 1.9.3 does weird things to encoding during gsub
  encoding ||= string.encoding.to_s

  # Unescaped have an even number of backslashes in front of them
  # because the double-quote is included, the unescaped quotes are where the size is odd
  nb_unescaped_quote = string.scan(/\\*"/).select { |s| s.size.odd? }.size

  raise 'unterminated dumped string' if nb_unescaped_quote == 1

  if string[-1] != '"' || nb_unescaped_quote > 2
    raise %(invalid dumped string; not wrapped with '"' nor '"...".force_encoding("...")' form)
  end

  string = string[1...-1]

  if RUBY_VERSION >= '1.9'
    # Look-arounds are not supported in ruby 1.8. Using a string with Regexp avoids the SyntaxError in 1.8.7
    # \xY, \x3Y and finishing with \x
    regex = Regexp.new("(?<!\\)(?:\\\\)*\\x(?![0-9a-f]{2})".gsub('\\', '\\\\\\\\'), Regexp::IGNORECASE)
    raise 'invalid hex escape' if string[regex]
  end

  # The real #undump ignores the \C, \c and \M escapes
  # Code injection is avoided by:
  #   * only allowing \u to have {}, so \\\\#{injection} will not eval the injection
  #   * only allowing the first character after the \\ to not be alpha/num/space, so \\\\#@inst_var_access is ignored
  # To reduce the number of calls to eval a little, we wrap everything in a (...)+ so that consecutive escapes are
  # handled at the same time.
  result = string.gsub(/(\\+(u\{[\w ]+\}|[^cCM]\w*))+/) do |s|
    begin
      eval("\"#{s}\"")  # "body"
    rescue SyntaxError => e
      raise RuntimeError, e.message, e.backtrace
    end
  end

  if encoding
    begin
      Encoding.find(encoding)
    rescue ArgumentError
      raise "dumped string has unknown encoding name"
    end
    result = result.force_encoding(encoding)
  end
  result
end

#unicode_normalize(form = :nfc) ⇒ Object



6
7
8
9
10
11
12
13
14
# File 'lib/backports/2.2.0/string/unicode_normalize.rb', line 6

def unicode_normalize(form = :nfc)
  require 'backports/tools/normalize' unless defined? UnicodeNormalize
  ## The following line can be uncommented to avoid repeated checking for
  ## UnicodeNormalize. However, tests didn't show any noticeable speedup
  ## when doing this. This comment also applies to the commented out lines
  ## in String#unicode_normalize! and String#unicode_normalized?.
  # String.send(:define_method, :unicode_normalize, ->(form = :nfc) { UnicodeNormalize.normalize(self, form) } )
  UnicodeNormalize.normalize(self, form)
end

#unicode_normalize!(form = :nfc) ⇒ Object



16
17
18
19
20
# File 'lib/backports/2.2.0/string/unicode_normalize.rb', line 16

def unicode_normalize!(form = :nfc)
  require 'backports/tools/normalize' unless defined? UnicodeNormalize
  # String.send(:define_method, :unicode_normalize!, ->(form = :nfc) { replace(unicode_normalize(form)) } )
  replace(unicode_normalize(form))
end

#unicode_normalized?(form = :nfc) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
25
26
# File 'lib/backports/2.2.0/string/unicode_normalize.rb', line 22

def unicode_normalized?(form = :nfc)
  require 'backports/tools/normalize' unless defined? UnicodeNormalize
  # String.send(:define_method, :unicode_normalized?, ->(form = :nfc) { UnicodeNormalize.normalized?(self, form) } )
  UnicodeNormalize.normalized?(self, form)
end

#unpack1(fmt) ⇒ Object



3
4
5
# File 'lib/backports/2.4.0/string/unpack1.rb', line 3

def unpack1(fmt)
  unpack(fmt)[0]
end

#upto_with_exclusive(to, excl = false) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/backports/1.8.7/string/upto.rb', line 6

def upto_with_exclusive(to, excl=false)
  return upto_without_exclusive(to){|s| yield s} if block_given? && !excl
  r = Range.new(self, to, excl)
  return r.to_enum unless block_given?
  r.each{|s| yield s}
  self
end