Class: InterFAX::File

Inherits:
Object
  • Object
show all
Defined in:
lib/interfax/file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, location, options = {}) ⇒ File

Returns a new instance of File.



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/interfax/file.rb', line 4

def initialize client, location, options = {}
  self.client = client
  self.chunk_size = options[:chunk_size] || 1024*1024

  if options[:mime_type]
    initialize_binary(location, options[:mime_type])
  elsif location.start_with?('http://') || location.start_with?('https://')
    initialize_url(location)
  else
    initialize_path(location)
  end
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



2
3
4
# File 'lib/interfax/file.rb', line 2

def body
  @body
end

#chunk_sizeObject

Returns the value of attribute chunk_size.



2
3
4
# File 'lib/interfax/file.rb', line 2

def chunk_size
  @chunk_size
end

#clientObject

Returns the value of attribute client.



2
3
4
# File 'lib/interfax/file.rb', line 2

def client
  @client
end

#headerObject

Returns the value of attribute header.



2
3
4
# File 'lib/interfax/file.rb', line 2

def header
  @header
end

Instance Method Details

#create_document(data, mime_type) ⇒ Object



52
53
54
55
# File 'lib/interfax/file.rb', line 52

def create_document data, mime_type
  extension = MimeMagic::EXTENSIONS.select {|k,v| v == mime_type.to_s}.keys.first
  client.documents.create("upload-#{Time.now.to_i}.#{extension}", data.length)
end

#initialize_binary(data, mime_type) ⇒ Object



17
18
19
20
21
# File 'lib/interfax/file.rb', line 17

def initialize_binary(data, mime_type)
  return initialize_document(data, mime_type) if data.length > chunk_size
  self.header = "Content-Type: #{mime_type}"
  self.body = data
end

#initialize_document(data, mime_type) ⇒ Object



36
37
38
39
40
# File 'lib/interfax/file.rb', line 36

def initialize_document(data, mime_type)
  document = create_document(data, mime_type)
  upload(document, data)
  initialize_url(document.uri)
end

#initialize_path(path) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/interfax/file.rb', line 28

def initialize_path(path)
  file = File.open(path)
  mime_type = MimeMagic.by_magic(file) || MimeMagic.by_path(file)
  data = File.open(path, 'rb').read

  initialize_binary(data, mime_type)
end

#initialize_url(url) ⇒ Object



23
24
25
26
# File 'lib/interfax/file.rb', line 23

def initialize_url(url)
  self.header = "Content-Location: #{url}"
  self.body = nil
end

#upload(document, data) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/interfax/file.rb', line 42

def upload document, data
  cursor = 0
  data.bytes.each_slice(chunk_size) do |slice|
    chunk = slice.pack("C*")
    next_cursor = cursor + chunk.length
    document.upload(cursor, next_cursor - 1, chunk)
    cursor = next_cursor
  end
end