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 if limit == 0
45 ''
46 elsif limit >= size
47 self
48 else
49 mb_chars[0...limit].to_s
50 end
51 end
52
53 # Returns the last character of the string or the last +limit+ characters.
54 #
55 # Examples:
56 # "hello".last # => "o"
57 # "hello".last(2) # => "lo"
58 # "hello".last(10) # => "hello"
59 def last(limit = 1)
60 if limit == 0
61 ''
62 elsif limit >= size
63 self
64 else
65 mb_chars[(-limit)..-1].to_s
66 end
67 end
68 end
69 else
70 module Access #:nodoc:
71 def at(position)
72 self[position]
73 end
74
75 def from(position)
76 self[position..-1]
77 end
78
79 def to(position)
80 self[0..position]
81 end
82
83 def first(limit = 1)
84 if limit == 0
85 ''
86 elsif limit >= size
87 self
88 else
89 to(limit - 1)
90 end
91 end
92
93 def last(limit = 1)
94 if limit == 0
95 ''
96 elsif limit >= size
97 self
98 else
99 from(-limit)
100 end
101 end
102 end
103 end
104 end
105 end
106 end