philiprehberger-truncate

Tests Gem Version Last updated

Smart string truncation with word boundaries, HTML safety, and multi-byte support

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-truncate"

Or install directly:

gem install philiprehberger-truncate

Usage

require "philiprehberger/truncate"

Philiprehberger::Truncate.words('one two three four five', 3)
# => "one two three..."

Character Truncation

Truncate to a character limit, breaking at the nearest word boundary:

Philiprehberger::Truncate.chars('hello beautiful world', 20)
# => "hello beautiful..."

# Custom omission string
Philiprehberger::Truncate.chars('hello beautiful world', 20, omission: ' [more]')
# => "hello beautiful [more]"

Sentence Truncation

Keep the first N complete sentences:

Philiprehberger::Truncate.sentences('First sentence. Second sentence. Third.', 2)
# => "First sentence. Second sentence...."

HTML-Safe Truncation

Truncate by visible characters while preserving and closing HTML tags:

Philiprehberger::Truncate.html('<p><strong>hello world</strong></p>', 5)
# => "<p><strong>hello...</strong></p>"

Line Truncation

text = "Line one\nLine two\nLine three\nLine four"
Philiprehberger::Truncate.lines(text, 2)
# => "Line one\nLine two..."

Strip HTML and Truncate

Strip HTML tags, decode entities, collapse whitespace, and truncate the resulting plain text:

Philiprehberger::Truncate.strip_html('<p>Hello <strong>world</strong></p>', 10)
# => "Hello..."

# Entity decoding
Philiprehberger::Truncate.strip_html('Tom &amp; Jerry are &lt;friends&gt;', 100)
# => "Tom & Jerry are <friends>"

# Custom omission
Philiprehberger::Truncate.strip_html('<p>hello beautiful world</p>', 14, omission: '')
# => "hello beautiful …"

Position Control

Control where the omission appears — :end (default), :start, or :middle:

text = "one two three four five"

Philiprehberger::Truncate.words(text, 3, position: :end)
# => "one two three..."

Philiprehberger::Truncate.words(text, 3, position: :start)
# => "...three four five"

Philiprehberger::Truncate.words(text, 4, position: :middle)
# => "one two...four five"

API

Method Description
Truncate.words(text, count, omission:, position:) Truncate text to N words
Truncate.chars(text, count, omission:, position:) Truncate text to N characters at a word boundary
Truncate.sentences(text, count, omission:, position:) Truncate text to N sentences
Truncate.lines(text, count, omission:) Truncate text to N lines
Truncate.html(html, char_count, omission:) HTML-safe truncation that preserves and closes tags
Truncate.strip_html(html, length, omission:) Strip HTML tags, decode entities, and truncate plain text

Development

bundle install
bundle exec rspec
bundle exec rubocop

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT