Class: Cifrado::FileSplitter

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/cifrado/file_splitter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils

#calculate_chunks, #clean_object_name, #decrypt_filename, #encrypt_filename, #humanize_bytes, #mime_type, #prettify_backtrace, #unix_time

Constructor Details

#initialize(filename, chunk_number = nil, cache_dir = Cifrado::Config.instance.cache_dir) ⇒ FileSplitter

FileSplitter.new(“elfari.webm”, 10).split

Parameters:

  • file (String)

    path to split

  • number (Integer)

    of chunks

  • Destination (String)

    directory of the chunks

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/cifrado/file_splitter.rb', line 14

def initialize(filename, 
               chunk_number = nil, 
               cache_dir = Cifrado::Config.instance.cache_dir)
  raise ArgumentError.new unless File.exist?(filename)
  @filename = File.basename filename
  @source = filename
  @chunk_number = chunk_number || calculate_chunks(filename)
  
  # when we are splitting a file into a given number of chunks, 
  # the last chunk could be bigger than the others
  @each_size, @extra = File.size(filename).divmod(@chunk_number)
  @cache_dir = File.expand_path cache_dir
  @chunk_suffix = "/segments/#{'%.2f' % File.mtime(filename).to_f}/#{File.size(filename)}/"
end

Instance Attribute Details

#cache_dirObject (readonly)

Returns the value of attribute cache_dir.



6
7
8
# File 'lib/cifrado/file_splitter.rb', line 6

def cache_dir
  @cache_dir
end

#chunk_suffixObject

Returns the value of attribute chunk_suffix.



7
8
9
# File 'lib/cifrado/file_splitter.rb', line 7

def chunk_suffix
  @chunk_suffix
end

Instance Method Details

#splitObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/cifrado/file_splitter.rb', line 29

def split
  file = File.new(@source, "rb")
  # create cache directory
  unless File.directory?(@cache_dir)
    Log.debug "Creating cache dir: #{@cache_dir}"
    FileUtils.mkdir_p(@cache_dir) 
  end

  chunks = []
  byte_count = 0
  chunk_n = 1
  chunk_name = @filename + "#{@chunk_suffix.gsub('/','-')}"
  chunk = File.join(@cache_dir, "#{chunk_name}#{'%08d' % chunk_n}")
  chunk_f = File.open(chunk, "wb")
  while read = file.read(4096) do
    if byte_count >= @each_size
      chunk_f.close
      chunks << chunk
      yield chunk_n, chunk if block_given?
      chunk_n += 1
      chunk = File.join(@cache_dir, "#{chunk_name}#{'%08d' % chunk_n}")
      chunk_f = File.open(chunk, "wb")
      byte_count = 0
    end
    chunk_f << read
    byte_count += 4096
  end
  chunk_f.flush
  yield chunk_n, chunk if block_given?
  chunks << chunk
  chunks
ensure
  chunk_f.close unless chunk_f.closed?
  file.close unless file.closed?
end