lib/ChunkyText/chunker.rb in ChunkyText-0.0.1 vs lib/ChunkyText/chunker.rb in ChunkyText-0.0.2

- old
+ new

@@ -1,45 +1,51 @@ module ChunkyText class Chunker + + PREPEND_COUNT = 6 - attr_reader :max_length, :chunk_array, :get_chunk + attr_reader :max_length, :chunk_array, :get_chunk, :elipse attr_accessor :string - def initialize(string, max_length) + def initialize(string, max_length, elipse = "(...)") @string = string - @max_length = max_length + @elipse = elipse + @max_length = max_length - elipse.length - 1 end - def get_chunk(input_string) - smaller_string = input_string.slice(0,max_length) + def get_chunk(input_string) + smaller_string = input_string.slice(0,max_length - PREPEND_COUNT) - if last_punctuation_mark(smaller_string) - smaller_string.slice(0,last_punctuation_mark(smaller_string) + 1) + 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 - array << get_chunk(input_string) - - input_string.slice!(0..max_length) + 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 + + array.map!.with_index do |chunk, i| + "(#{i + 1}/#{array.count}) " + chunk + end end private - def last_punctuation_mark(string) - punctuation_mark_positions = [] - ['!','?','.'].each do |p_mark| - punctuation_mark_positions << string.rindex(p_mark) - end - punctuation_mark_positions.reject! { |item| item == nil } - punctuation_mark_positions.max + def last_space(string) + position = string.rindex /\s/ end end end \ No newline at end of file