Class: String

Inherits:
Object show all
Defined in:
lib/droiuby/support/object/blank.rb,
lib/droiuby/support/string/access.rb,
lib/droiuby/support/string/indent.rb,
lib/droiuby/support/string/droiuby.rb,
lib/droiuby/support/string/exclude.rb,
lib/droiuby/support/string/filters.rb,
lib/droiuby/support/string/behavior.rb,
lib/droiuby/support/string/starts_ends_with.rb

Instance Method Summary collapse

Instance Method Details

#acts_like_string?Boolean

Enable more predictable duck-typing on String-like classes. See Object#acts_like?.

Returns:

  • (Boolean)


3
4
5
# File 'lib/droiuby/support/string/behavior.rb', line 3

def acts_like_string?
  true
end

#at(position) ⇒ Object

If you pass a single Fixnum, returns a substring of one character at that position. The first character of the string is at position 0, the next at position 1, and so on. If a range is supplied, a substring containing characters at offsets given by the range is returned. In both cases, if an offset is negative, it is counted from the end of the string. Returns nil if the initial offset falls outside the string. Returns an empty string if the beginning of the range is greater than the end of the string.

str = "hello"
str.at(0)      #=> "h"
str.at(1..3)   #=> "ell"
str.at(-2)     #=> "l"
str.at(-2..-1) #=> "lo"
str.at(5)      #=> nil
str.at(5..-1)  #=> ""

If a Regexp is given, the matching portion of the string is returned. If a String is given, that given string is returned if it occurs in the string. In both cases, nil is returned if there is no match.

str = "hello"
str.at(/lo/) #=> "lo"
str.at(/ol/) #=> nil
str.at("lo") #=> "lo"
str.at("ol") #=> nil


27
28
29
# File 'lib/droiuby/support/string/access.rb', line 27

def at(position)
  self[position]
end

#blank?Boolean

A string is blank if it’s empty or contains whitespaces only:

''.blank?                 # => true
'   '.blank?              # => true
' '.blank?               # => true
' something here '.blank? # => false

Returns:

  • (Boolean)


92
93
94
# File 'lib/droiuby/support/object/blank.rb', line 92

def blank?
  self !~ /[^[:space:]]/
end

#camelize(first_letter_in_uppercase = true) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/droiuby/support/string/droiuby.rb', line 3

def camelize(first_letter_in_uppercase = true)
  if first_letter_in_uppercase
    self.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase }
  else
    self.first + camelize(self)[1..-1]
  end
end

#constantizeObject



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
# File 'lib/droiuby/support/string/droiuby.rb', line 27

def constantize
  names = self.split('::')
  names.shift if names.empty? || names.first.empty?
  index = 1
  names.inject(Object) do |constant, name|
    if constant == Object
      constant.const_get(name)
    else
      begin
        candidate = constant.const_get(name)
      rescue NameError => e
        Object.const_missing(names[0..index].join('::'))
        candidate = constant.const_get(name)
      end
      index += 1
      next candidate if constant.const_defined?(name, false)
      next candidate unless Object.const_defined?(name)

      # Go down the ancestors to check it it's owned
      # directly before we reach Object or the end of ancestors.
      constant = constant.ancestors.inject do |const, ancestor|
        break const    if ancestor == Object
        break ancestor if ancestor.const_defined?(name, false)
        const
      end

      # owner is in Object, so raise
      constant.const_get(name, false)

    end
  end
end

#exclude?(string) ⇒ Boolean

The inverse of String#include?. Returns true if the string does not include the other string.

"hello".exclude? "lo" #=> false
"hello".exclude? "ol" #=> true
"hello".exclude? ?h   #=> false

Returns:

  • (Boolean)


8
9
10
# File 'lib/droiuby/support/string/exclude.rb', line 8

def exclude?(string)
  !include?(string)
end

#first(limit = 1) ⇒ Object

Returns the first character. If a limit is supplied, returns a substring from the beginning of the string until it reaches the limit value. If the given limit is greater than or equal to the string length, returns self.

str = "hello"
str.first    #=> "h"
str.first(1) #=> "h"
str.first(2) #=> "he"
str.first(0) #=> ""
str.first(6) #=> "hello"


75
76
77
78
79
80
81
82
83
# File 'lib/droiuby/support/string/access.rb', line 75

def first(limit = 1)
  if limit == 0
    ''
  elsif limit >= size
    self
  else
    to(limit - 1)
  end
end

#from(position) ⇒ Object

Returns a substring from the given position to the end of the string. If the position is negative, it is counted from the end of the string.

str = "hello"
str.from(0)  #=> "hello"
str.from(3)  #=> "lo"
str.from(-2) #=> "lo"

You can mix it with to method and do fun things like:

str = "hello"
str.from(0).to(-1) #=> "hello"
str.from(1).to(-2) #=> "ell"


44
45
46
# File 'lib/droiuby/support/string/access.rb', line 44

def from(position)
  self[position..-1]
end

#indent(amount, indent_string = nil, indent_empty_lines = false) ⇒ Object

Indents the lines in the receiver:

<<EOS.indent(2)
def some_method
  some_code
end
EOS
# =>
  def some_method
    some_code
  end

The second argument, indent_string, specifies which indent string to use. The default is nil, which tells the method to make a guess by peeking at the first indented line, and fallback to a space if there is none.

"  foo".indent(2)        # => "    foo"
"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
"foo".indent(2, "\t")    # => "\t\tfoo"

While indent_string is typically one space or tab, it may be any string.

The third argument, indent_empty_lines, is a flag that says whether empty lines should be indented. Default is false.

"foo\n\nbar".indent(2)            # => "  foo\n\n  bar"
"foo\n\nbar".indent(2, nil, true) # => "  foo\n  \n  bar"


40
41
42
# File 'lib/droiuby/support/string/indent.rb', line 40

def indent(amount, indent_string=nil, indent_empty_lines=false)
  dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
end

#indent!(amount, indent_string = nil, indent_empty_lines = false) ⇒ Object

Same as indent, except it indents the receiver in-place.

Returns the indented string, or nil if there was nothing to indent.



5
6
7
8
9
# File 'lib/droiuby/support/string/indent.rb', line 5

def indent!(amount, indent_string=nil, indent_empty_lines=false)
  indent_string = indent_string || self[/^[ \t]/] || ' '
  re = indent_empty_lines ? /^/ : /^(?!$)/
  gsub!(re, indent_string * amount)
end

#last(limit = 1) ⇒ Object

Returns the last character of the string. If a limit is supplied, returns a substring from the end of the string until it reaches the limit value (counting backwards). If the given limit is greater than or equal to the string length, returns self.

str = "hello"
str.last    #=> "o"
str.last(1) #=> "o"
str.last(2) #=> "lo"
str.last(0) #=> ""
str.last(6) #=> "hello"


95
96
97
98
99
100
101
102
103
# File 'lib/droiuby/support/string/access.rb', line 95

def last(limit = 1)
  if limit == 0
    ''
  elsif limit >= size
    self
  else
    from(-limit)
  end
end

#squishObject

Returns the string, first removing all whitespace on both ends of the string, and then changing remaining consecutive whitespace groups into one space each.

Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E).

%{ Multi-line
   string }.squish                   # => "Multi-line string"
" foo   bar    \n   \t   boo".squish # => "foo bar boo"


11
12
13
# File 'lib/droiuby/support/string/filters.rb', line 11

def squish
  dup.squish!
end

#squish!Object

Performs a destructive squish. See String#squish.



16
17
18
19
20
21
# File 'lib/droiuby/support/string/filters.rb', line 16

def squish!
  gsub!(/\A[[:space:]]+/, '')
  gsub!(/[[:space:]]+\z/, '')
  gsub!(/[[:space:]]+/, ' ')
  self
end

#to(position) ⇒ Object

Returns a substring from the beginning of the string to the given position. If the position is negative, it is counted from the end of the string.

str = "hello"
str.to(0)  #=> "h"
str.to(3)  #=> "hell"
str.to(-2) #=> "hell"

You can mix it with from method and do fun things like:

str = "hello"
str.from(0).to(-1) #=> "hello"
str.from(1).to(-2) #=> "ell"


61
62
63
# File 'lib/droiuby/support/string/access.rb', line 61

def to(position)
  self[0..position]
end

#to_colorObject



15
16
17
# File 'lib/droiuby/support/string/droiuby.rb', line 15

def to_color
  Java::android.graphics.Color.parseColor(self)
end

#to_pixelsObject



11
12
13
# File 'lib/droiuby/support/string/droiuby.rb', line 11

def to_pixels
  Java::com.droiuby.client.core.builder.ActivityBuilder.toPixels(_current_activity, self)
end

#truncate(truncate_at, options = {}) ⇒ Object

Truncates a given text after a given length if text is longer than length:

'Once upon a time in a world far far away'.truncate(27)
# => "Once upon a time in a wo..."

Pass a string or regexp :separator to truncate text at a natural break:

'Once upon a time in a world far far away'.truncate(27, separator: ' ')
# => "Once upon a time in a..."

'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
# => "Once upon a time in a..."

The last characters will be replaced with the :omission string (defaults to “…”) for a total length not exceeding length:

'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
# => "And they f... (continued)"


41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/droiuby/support/string/filters.rb', line 41

def truncate(truncate_at, options = {})
  return dup unless length > truncate_at

  options[:omission] ||= '...'
  length_with_room_for_omission = truncate_at - options[:omission].length
  stop = \
    if options[:separator]
      rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
    else
      length_with_room_for_omission
    end

  "#{self[0...stop]}#{options[:omission]}"
end

#underscoreObject



19
20
21
22
23
24
25
# File 'lib/droiuby/support/string/droiuby.rb', line 19

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