Sha256: 39c867844453060b7ec2795d327e9be6d272354ee93f419047e4dfe81a1d6855

Contents?: true

Size: 1.37 KB

Versions: 4

Compression:

Stored size: 1.37 KB

Contents

module DmAdapterSimpledb
  class ChunkedString < String
    MAX_CHUNK_SIZE = 1019

    def self.valid?(values)
      values.all?{|v| v =~ /^\d{4}:/}
    end

    def initialize(string_or_array)
      case string_or_array
      when Array then super(chunks_to_string(string_or_array))
      else super(string_or_array)
      end
    end

    def to_ary
      string_to_chunks(self)
    end

    alias_method :to_a, :to_ary
    
    private

    def string_to_chunks(value)
      return [value] if value.size <= 1019
      chunks = value.to_s.scan(%r/.{1,1019}/m) # 1024 - '1024:'.size
      i = -1
      fmt = '%04d:'
      chunks.map!{|chunk| [(fmt % (i += 1)), chunk].join}
      raise ArgumentError, 'that is just too big yo!' if chunks.size >= 256
      chunks
    end
    
    def chunks_to_string(value)
      begin
        chunks =
          Array(value).flatten.map do |chunk|
          index, text = chunk.split(%r/:/, 2)
          [Float(index).to_i, text]
        end
        chunks.replace chunks.sort_by{|index, text| index}
        string_result = chunks.map!{|index, text| text}.join
        string_result
      rescue ArgumentError, TypeError
        #return original value, they could have put strings in the system not
        #using the adapter or previous versions that are larger than chunk size,
        #but less than 1024
        value.to_s
      end
    end

    
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dm-adapter-simpledb-1.5.0 lib/dm-adapter-simpledb/chunked_string.rb
dm-adapter-simpledb-1.4.0 lib/dm-adapter-simpledb/chunked_string.rb
dm-adapter-simpledb-1.3.0 lib/dm-adapter-simpledb/chunked_string.rb
dm-adapter-simpledb-1.2.0 lib/dm-adapter-simpledb/chunked_string.rb