Module: Peppercorn::String

Included in:
String
Defined in:
lib/peppercorn/string.rb

Overview

Peppercorn extension to the String class

Instance Method Summary collapse

Instance Method Details

#peppercorn_truncate(length = 30, opts = {}) ⇒ String

Truncate a string to “length” words

Parameters:

  • length (Fixnum) (defaults to: 30)

    the number of word to truncate on

  • opts (Hash) (defaults to: {})

    hash of truncation options

Options Hash (opts):

  • :tail (#to_s, nil) — default: "…"

    the object to append to the truncated string

Returns:

  • (String)

    the truncated string

Since:

  • 0.0.3



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/peppercorn/string.rb', line 13

def peppercorn_truncate(length=30, opts={})
  opts = Peppercorn::DEFAULT_TRUNCATION_OPTIONS.merge(opts)
  tokens = scan(/\W*\w+\W*/)
  string_tokens = tokens[0...length]
  string = string_tokens.join
  overran = length <= tokens.size
  string = string.strip_end if opts[:strip]
  string << opts[:tail].to_s if overran
  if opts[:return_node]
    string = Nokogiri::HTML::DocumentFragment.parse(string)
    string = string.child if string.children.size == 1
  end
  return opts[:return_hash] ? {:text => string, :overran => overran, :count => [length, tokens.size].min} : string
end

#strip_endString

Strips all whitespaces from the end of the string

Returns:

  • (String)

    the stripped version of the string

Since:

  • 0.0.1



37
38
39
# File 'lib/peppercorn/string.rb', line 37

def strip_end
  return rstrip
end

#strip_htmlString

Returns the string with all HTML tags removed

Returns:

  • (String)

    the string stripped of all HTML

Since:

  • 0.0.1



44
45
46
# File 'lib/peppercorn/string.rb', line 44

def strip_html
  return Nokogiri::HTML::DocumentFragment.parse(self).inner_text
end

#truncate(length = 30, opts = {}) ⇒ Object

Alias for #peppercorn_truncate

Since:

  • 0.0.1



30
31
32
# File 'lib/peppercorn/string.rb', line 30

def truncate(length=30, opts={})
  peppercorn_truncate(length, opts)
end

#truncate_html(length = 30, opts = {}) ⇒ String

Truncate a string of html to “length” words

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

Returns:

  • (String)

    the truncated html

Since:

  • 0.0.1



53
54
55
# File 'lib/peppercorn/string.rb', line 53

def truncate_html(length=30, opts={})
  Nokogiri::HTML::DocumentFragment.parse(self).truncate(length, opts)
end