Class: String
- Defined in:
- lib/core_ext/object/blank.rb,
lib/core_ext/string/truncate.rb
Constant Summary collapse
- BLANK_RE =
rails may be loaded by client
/\A[[:space:]]*\z/.freeze
Instance Method Summary collapse
-
#blank? ⇒ true, false
A string is blank if it’s empty or contains whitespaces only:.
- #truncate(maximum_length, omission: '…', mode: :right) ⇒ Object
-
#truncate_middle(maximum_length = 3, separator = '…') ⇒ Object
Truncates the middle, leaving portions from start & end see stackoverflow.com/a/62713671.
-
#truncate_right(truncate_at, options = {}) ⇒ Object
File activesupport/lib/active_support/core_ext/string/filters.rb, line 66.
Instance Method Details
#blank? ⇒ true, false
A string is blank if it’s empty or contains whitespaces only:
''.blank? # => true
' '.blank? # => true
"\t\n\r".blank? # => true
' blah '.blank? # => false
Unicode whitespace is supported:
"\u00a0".blank? # => true
115 116 117 118 119 120 |
# File 'lib/core_ext/object/blank.rb', line 115 def blank? # The regexp that matches blank strings is expensive. For the case of empty # strings we can speed up this method (~3.5x) with an empty? call. The # penalty for the rest of strings is marginal. empty? || BLANK_RE === self end |
#truncate(maximum_length, omission: '…', mode: :right) ⇒ Object
2 3 4 5 6 7 8 9 10 11 |
# File 'lib/core_ext/string/truncate.rb', line 2 def truncate(maximum_length, omission: '…', mode: :right) case mode when :right, 'right' truncate_right(maximum_length, omission: omission) when :middle, 'middle' truncate_middle(maximum_length, omission) else raise ArgumentError, "Unsupported mode (#{mode}), expected [:middle, :right]." end end |
#truncate_middle(maximum_length = 3, separator = '…') ⇒ Object
Truncates the middle, leaving portions from start & end see stackoverflow.com/a/62713671
30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/core_ext/string/truncate.rb', line 30 def truncate_middle(maximum_length = 3, separator = '…') return '' if maximum_length.zero? return self if length <= maximum_length middle_length = length - maximum_length + separator.length edges_length = (length - middle_length) / 2.0 left_length = edges_length.ceil right_length = edges_length.floor left_string = left_length.zero? ? '' : self[0, left_length] right_string = right_length.zero? ? '' : self[-right_length, right_length] "#{left_string}#{separator}#{right_string}" end |
#truncate_right(truncate_at, options = {}) ⇒ Object
File activesupport/lib/active_support/core_ext/string/filters.rb, line 66
14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/core_ext/string/truncate.rb', line 14 def truncate_right(truncate_at, = {}) return dup unless length > truncate_at omission = [:omission] || '…' length_with_room_for_omission = truncate_at - omission.length stop = if [:separator] rindex([:separator], length_with_room_for_omission) || length_with_room_for_omission else length_with_room_for_omission end +"#{self[0, stop]}#{omission}" end |