From 10db166aef3ac99183b8360512f62a1a2685ae40 Mon Sep 17 00:00:00 2001 From: Rashmi Yadav Date: Sun, 24 Aug 2014 01:31:37 +0200 Subject: [ci skip] document truncate_words --- guides/source/active_support_core_extensions.md | 33 +++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'guides') 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. -- cgit v1.2.3