Sha256: 0dabe98fd9489f2bd40d043b711b2be268a08b16ae6ad47211fc1b6204f1b0eb

Contents?: true

Size: 1.39 KB

Versions: 11

Compression:

Stored size: 1.39 KB

Contents

module Abbreviato
  DEFAULT_OPTIONS = {
      max_length: 30,
      tail: '…',
      fragment: true
  }.freeze

  # 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 (...).
  #
  # @param [String] source the XML source to truncate
  # @param [Hash] user_options truncation options
  # @option user_options [Integer] :max_length Maximum length
  # @option user_options [String] :tail Text to append when the truncation happens
  # @option user_options [Boolean] :fragment 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`.
  # @return [[String] the truncated string, [boolean] whether the string was truncated]
  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
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
abbreviato-0.9.4 lib/abbreviato/abbreviato.rb
abbreviato-0.9.3 lib/abbreviato/abbreviato.rb
abbreviato-0.9.2 lib/abbreviato/abbreviato.rb
abbreviato-0.9.1 lib/abbreviato/abbreviato.rb
abbreviato-0.9.0 lib/abbreviato/abbreviato.rb
abbreviato-0.8.9 lib/abbreviato/abbreviato.rb
abbreviato-0.8.8 lib/abbreviato/abbreviato.rb
abbreviato-0.8.5 lib/abbreviato/abbreviato.rb
abbreviato-0.8.4 lib/abbreviato/abbreviato.rb
abbreviato-0.8.3 lib/abbreviato/abbreviato.rb
abbreviato-0.8.2 lib/abbreviato/abbreviato.rb