Class: Concen::GridFile

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document, Mongoid::Timestamps
Defined in:
app/models/concen/grid_file.rb

Instance Method Summary collapse

Instance Method Details

#content_type_for(filename) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'app/models/concen/grid_file.rb', line 68

def content_type_for(filename)
  content_type = MIME::Types.type_for(filename).first.to_s

  # Special cases when mime-types fails to recognize
  content_type = "video/mp4" if filename.include?(".mp4")
  content_type = "video/x-m4v" if filename.include?(".m4v")

  return content_type
end

#pathObject



19
20
21
# File 'app/models/concen/grid_file.rb', line 19

def path
  "/gridfs/" + self.filename
end

#readObject



29
30
31
32
# File 'app/models/concen/grid_file.rb', line 29

def read
  grid = Mongo::Grid.new(Mongoid.database)
  grid.get(self.grid_id).read
end

#sizeObject



34
35
36
37
# File 'app/models/concen/grid_file.rb', line 34

def size
  grid = Mongo::Grid.new(Mongoid.database)
  grid.get(self.grid_id).file_length
end

#store(content, filename) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'app/models/concen/grid_file.rb', line 44

def store(content, filename)
  grid = Mongo::Grid.new(Mongoid.database)

  # First, delete if a GridFS file already exists.
  # There is no update.
  grid.delete(self.grid_id) if self.grid_id

  original_filename = filename.dup
  file_extension = File.extname(original_filename).downcase
  content_type = content_type_for original_filename

  # Pre generate ObjectId for the new GridFS file.
  grid_id = BSON::ObjectId.new

  filename = File.basename(original_filename, file_extension).downcase.parameterize.gsub("_", "-")
  filename = "#{grid_id.to_s}-#{filename}#{file_extension}"

  if grid.put(content, :_id => grid_id, :filename => filename, :content_type => content_type, :safe => true)
    self.update_attributes(:grid_id => grid_id, :filename => filename, :original_filename => original_filename)
  else
    return false
  end
end

#text?Boolean

Returns:

  • (Boolean)


39
40
41
42
# File 'app/models/concen/grid_file.rb', line 39

def text?
  grid = Mongo::Grid.new(Mongoid.database)
  grid.get(self.grid_id).content_type.include?("text") || grid.get(self.grid_id).content_type.include?("javascript")
end

#url(root_url) ⇒ Object



23
24
25
26
27
# File 'app/models/concen/grid_file.rb', line 23

def url(root_url)
  root_url.gsub!("concen.", "") # Remove concen subdomain.
  root_url = root_url[0..-2] # Remove trailing slash.
  root_url + self.path
end