Froze rails gems
[depot.git] / vendor / rails / activesupport / lib / active_support / core_ext / string / access.rb
1 module ActiveSupport #:nodoc:
2 module CoreExtensions #:nodoc:
3 module String #:nodoc:
4 unless '1.9'.respond_to?(:force_encoding)
5 # Makes it easier to access parts of a string, such as specific characters and substrings.
6 module Access
7 # Returns the character at the +position+ treating the string as an array (where 0 is the first character).
8 #
9 # Examples:
10 # "hello".at(0) # => "h"
11 # "hello".at(4) # => "o"
12 # "hello".at(10) # => nil
13 def at(position)
14 mb_chars[position, 1].to_s
15 end
16
17 # Returns the remaining of the string from the +position+ treating the string as an array (where 0 is the first character).
18 #
19 # Examples:
20 # "hello".from(0) # => "hello"
21 # "hello".from(2) # => "llo"
22 # "hello".from(10) # => nil
23 def from(position)
24 mb_chars[position..-1].to_s
25 end
26
27 # Returns the beginning of the string up to the +position+ treating the string as an array (where 0 is the first character).
28 #
29 # Examples:
30 # "hello".to(0) # => "h"
31 # "hello".to(2) # => "hel"
32 # "hello".to(10) # => "hello"
33 def to(position)
34 mb_chars[0..position].to_s
35 end
36
37 # Returns the first character of the string or the first +limit+ characters.
38 #
39 # Examples:
40 # "hello".first # => "h"
41 # "hello".first(2) # => "he"
42 # "hello".first(10) # => "hello"
43 def first(limit = 1)
44 mb_chars[0..(limit - 1)].to_s
45 end
46
47 # Returns the last character of the string or the last +limit+ characters.
48 #
49 # Examples:
50 # "hello".last # => "o"
51 # "hello".last(2) # => "lo"
52 # "hello".last(10) # => "hello"
53 def last(limit = 1)
54 (mb_chars[(-limit)..-1] || self).to_s
55 end
56 end
57 else
58 module Access #:nodoc:
59 def at(position)
60 self[position]
61 end
62
63 def from(position)
64 self[position..-1]
65 end
66
67 def to(position)
68 self[0..position]
69 end
70
71 def first(limit = 1)
72 self[0..(limit - 1)]
73 end
74
75 def last(limit = 1)
76 from(-limit) || self
77 end
78 end
79 end
80 end
81 end
82 end