Module: TextHelper

Defined in:
app/helpers/text_helper.rb

Overview

Instance Method Summary collapse

Instance Method Details

#truncate_html(text, options = {}) ⇒ Object

Like the Rails truncate helper but doesn’t break HTML tags or entities.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'app/helpers/text_helper.rb', line 7

def truncate_html(text, options={})
  return if text.nil?

  length = options.delete(:length) || 30
  omission = options.delete(:omission).to_s || "..."
  text = text.to_s

  document = Hpricot(text)
  omission_length = Hpricot(omission).inner_text.chars.count
  content_length = document.inner_text.chars.count

  content_length > length ? document.truncate([length - omission_length, 0].max).inner_html + omission : text
end