class Abstractifier

Constants

DEFAULT_MAXIMUM_LENGTH
DEFAULT_MINIMUM_LENGTH

Attributes

elider[RW]
max_length[RW]
min_length[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/abstractifier.rb, line 9
def initialize(options = {})
  @min_length = options.fetch(:min, DEFAULT_MINIMUM_LENGTH)
  @max_length = options.fetch(:max, DEFAULT_MAXIMUM_LENGTH)
  @elider = options.fetch(:elider, '…')
end

Public Instance Methods

abstractify(string) click to toggle source
# File lib/abstractifier.rb, line 15
def abstractify(string)
  output = ''

  extract_sentences(string).each do |sentence|
    output << "#{sentence}. "
    break if output.length >= min_length
  end

  output = forcibly_truncate(output) if output.length > max_length
  output = tidy(output)

  output
end

Private Instance Methods

extract_sentences(string) click to toggle source
# File lib/abstractifier.rb, line 37
def extract_sentences(string)
  string
    .gsub(/[[:space:]]+/, ' ')
    .split(/\.(?:\s|$)/)
end
forcibly_truncate(string) click to toggle source
# File lib/abstractifier.rb, line 31
def forcibly_truncate(string)
  truncated = string[0, max_length + 1].strip.split(/\s\b\w+$/).first

  strip_trailing_punctuation(truncated)
end
strip_trailing_punctuation(string) click to toggle source
# File lib/abstractifier.rb, line 43
def strip_trailing_punctuation(string)
  if string[-1] =~ /[\.\?\!]/
    string
  elsif string[-1] =~ /[[:punct:]]/
    string[0..-2] + elider
  else
    string + elider
  end
end
tidy(string) click to toggle source
# File lib/abstractifier.rb, line 53
def tidy(string)
  string
    .gsub(/[[:space:]]+/, ' ')
    .gsub(/[[:space:]](,|\.)/, '\1')
    .strip
end