Class: Document

Inherits:
MLS::Model show all
Defined in:
lib/mls/document.rb

Direct Known Subclasses

Image, PDF

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.create(file) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/mls/document.rb', line 3

def self.create(file)
  if doc = find_matching(file)
    doc
  else
    data, headers = Multipart::Post.prepare_query("document[file]" => file)
  
    req = Net::HTTP::Post.new("/documents")
    req.body = data
    req['Content-Type'] = headers['Content-Type']
  
    res = Document.connection.instance_variable_get(:@connection).send_request(req)
    instantiate(JSON.parse(res.body).select{|k,v| column_names.include?(k.to_s) })
  end
end

.find_matching(file) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/mls/document.rb', line 42

def self.find_matching(file)
  filename = file.original_filename if file.respond_to?(:original_filename)
  filename ||= File.basename(file.path)

  # If we can tell the possible mime-type from the filename, use the
  # first in the list; otherwise, use "application/octet-stream"
  content_type = file.content_type if file.respond_to?(:content_type)
  content_type ||= (MIME::Types.type_for(filename)[0] || MIME::Types["application/octet-stream"][0]).simplified

  matching_docs = Document.where(:filename => filename, :content_type => content_type, :size => file.size)
  if matching_docs.count > 0
    matching_docs = matching_docs.where(:md5 => Digest::MD5.file(file.path).hexdigest)
  end
  
  matching_docs.first
end

Instance Method Details

#aspect_ratioObject



37
38
39
40
# File 'lib/mls/document.rb', line 37

def aspect_ratio
  return nil if !width || !height
  return width.to_f / height.to_f
end

#heightObject



32
33
34
35
# File 'lib/mls/document.rb', line 32

def height
  return nil if !dimensions
  return dimensions.split('x')[1].to_i
end

#path(style = :original) ⇒ Object



22
23
24
# File 'lib/mls/document.rb', line 22

def path(style=:original)
  "/documents/#{hash_key}/#{style}#{File.extname(filename)}"
end

#url(style = :original) ⇒ Object



18
19
20
# File 'lib/mls/document.rb', line 18

def url(style=:original)
  MLS.config['document_host'] + path(style)
end

#widthObject



27
28
29
30
# File 'lib/mls/document.rb', line 27

def width
  return nil if !dimensions
  return dimensions.split('x')[0].to_i
end