Sha256: 8d700d668bd49faa4cabf39103ed9854f6e6f65abe7e523c8a2340381e9af3a4

Contents?: true

Size: 1.23 KB

Versions: 1

Compression:

Stored size: 1.23 KB

Contents

module ChunkyText
  class Chunker

    PREPEND_COUNT = 6
    
    attr_reader :max_length, :chunk_array, :get_chunk, :elipse
    attr_accessor :string

    def initialize(string, max_length, elipse = "(...)")
      @string = string
      @elipse = elipse
      @max_length = max_length - elipse.length - 1
    end 

    def get_chunk(input_string) 
      smaller_string = input_string.slice(0,max_length - PREPEND_COUNT)

      if last_space(smaller_string)
        smaller_string.slice(0,last_space(smaller_string) + 1)
      else
        smaller_string
      end
    end

    def chunk_array
      input_string = string.clone
      array = []
      while input_string.length > 0 do
        if input_string.length > max_length - PREPEND_COUNT 
          chunk = get_chunk(input_string)
          array <<  chunk + ' ' + elipse
          input_string.slice!(0..chunk.length - 1)
        else
          array << input_string
          break
        end
      end
      input_string = string.clone
      
      array.map!.with_index do |chunk, i|
        "(#{i + 1}/#{array.count}) " + chunk  
      end 
    end

    private

    def last_space(string)
      position = string.rindex /\s/
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ChunkyText-0.0.2 lib/ChunkyText/chunker.rb