Module: DashFu::Bee::Utils
- Included in:
- DashFu::Bee
- Defined in:
- lib/dash-fu/bee/utils.rb
Overview
Utility functions. Also accessible as instance methods in Bee.
Class Method Summary collapse
-
.escape_html(text) ⇒ Object
(also: h)
Shortcut for Rack::Utils.escape_html.
-
.truncate(text, length = 250, continue = "...") ⇒ Object
Truncates text value.
-
.truncate_html(html, limit = 250, ellipsis = "...") ⇒ Object
Truncates HTML without unbalanced elements/entities.
Class Method Details
.escape_html(text) ⇒ Object Also known as: h
Shortcut for Rack::Utils.escape_html
7 8 9 |
# File 'lib/dash-fu/bee/utils.rb', line 7 def escape_html(text) Rack::Utils.escape_html(text.to_s) end |
.truncate(text, length = 250, continue = "...") ⇒ Object
Truncates text value.
13 14 15 16 17 |
# File 'lib/dash-fu/bee/utils.rb', line 13 def truncate(text, length = 250, continue = "...") return text unless text.length > length trim = length - continue.length text[0,trim] + continue end |
.truncate_html(html, limit = 250, ellipsis = "...") ⇒ Object
Truncates HTML without unbalanced elements/entities.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/dash-fu/bee/utils.rb', line 20 def truncate_html(html, limit = 250, ellipsis = "...") # Inspiration: http://pastie.textmate.org/145402 ellipsis_length = Nokogiri::HTML.fragment(ellipsis).text.length truncate = lambda do |node, avail| node.children.each do |child| if avail <= 0 child.remove elsif child.text? source = child.parent.name == "pre" ? child.content : child.content.squeeze(" ") child.content = source[/^(.{0,#{avail}})(\s.*)?$/, 1] avail -= source.length elsif child.element? && !%w{script style}.include?(child.name) avail = truncate[child, avail] else child.remove end end avail end nodes = Nokogiri::HTML.fragment(html) left = truncate[nodes, limit - ellipsis_length] left < 0 ? nodes.to_html + ellipsis : nodes.to_html end |