Module: Abbreviato

Defined in:
lib/abbreviato/version.rb,
lib/abbreviato/abbreviato.rb

Constant Summary collapse

VERSION =
'0.9.4'.freeze
DEFAULT_OPTIONS =
{
    max_length: 30,
    tail: '…',
    fragment: true
}.freeze

Class Method Summary collapse

Class Method Details

.truncate(source = '', user_options = {}) ⇒ [String] the truncated string, [boolean] whether the string was truncated

Truncates the source XML string and returns the truncated XML and a boolean flag indicating whether any truncation took place. It will keep a valid XML structure and insert a tail text indicating the position where content was removed (…).

Parameters:

  • source (String) (defaults to: '')

    the XML source to truncate

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

    truncation options

Options Hash (user_options):

  • :max_length (Integer)

    Maximum length

  • :tail (String)

    Text to append when the truncation happens

  • :fragment (Boolean)

    Indicates whether the document to be truncated is an HTML fragment or an entire document (with ‘HTML`, `HEAD` & `BODY` tags). Setting to true prevents automatic addition of these tags if they are missing. Defaults to `true`.

Returns:

  • ([String] the truncated string, [boolean] whether the string was truncated)


20
21
22
23
24
25
26
# File 'lib/abbreviato/abbreviato.rb', line 20

def self.truncate(source = '', user_options = {})
  return [nil, false] if source.nil?
  truncated_sax_document = TruncatedSaxDocument.new(DEFAULT_OPTIONS.merge(user_options))
  parser = Nokogiri::HTML::SAX::Parser.new(truncated_sax_document)
  parser.parse(source) { |context| context.replace_entities = false }
  [truncated_sax_document.truncated_string.strip, truncated_sax_document.truncated]
end