aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/active_support_core_extensions.md
diff options
context:
space:
mode:
Diffstat (limited to 'guides/source/active_support_core_extensions.md')
-rw-r--r--guides/source/active_support_core_extensions.md33
1 files changed, 33 insertions, 0 deletions
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 08b46c62eb..0bdbf1d696 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -1310,6 +1310,39 @@ In above examples "dear" gets cut first, but then `:separator` prevents it.
NOTE: Defined in `active_support/core_ext/string/filters.rb`.
+### `truncate_words`
+
+The method `truncate_words` returns a copy of its receiver truncated after a given number of `words`:
+
+```ruby
+"Oh dear! Oh dear! I shall be late!".truncate_words(4)
+# => "Oh dear! Oh dear!..."
+```
+Ellipsis can be customized with the `:omission` option:
+
+```ruby
+"Oh dear! Oh dear! I shall be late!".truncate_words(4, omission: '…')
+# => "Oh dear! Oh dear!…"
+```
+
+Note in particular that truncation takes into account the length of the omission string.
+
+Pass a `:separator` to truncate the string at a natural break:
+
+```ruby
+"Oh dear! Oh dear! I shall be late!".truncate_words(4, separator: ' ')
+# => "Oh dear! Oh dear!..."
+```
+
+The option `:separator` can be a regexp:
+
+```ruby
+"Oh dear! Oh dear! I shall be late!".truncate_words(4, separator: /\s/)
+# => "Oh dear! Oh dear!..."
+```
+
+NOTE: Defined in `active_support/core_ext/string/filters.rb`.
+
### `inquiry`
The `inquiry` method converts a string into a `StringInquirer` object making equality checks prettier.