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
64
65
66
67
68
69
70
71
72
73
|
# File 'lib/congo/grip/has_attachment.rb', line 33
def has_grid_attachment(name, options = {})
configuration = { :path => ":class/:name/:id" }
configuration.update(options) if options.is_a?(Hash)
write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil?
attachment_definitions[name] = {}
after_save :save_attachments
before_destroy :destroy_attached_files
key "#{name}_size".to_sym, Integer
key "#{name}_path".to_sym, String
key "#{name}_name".to_sym, String
key "#{name}_content_type".to_sym, String
define_method(name) do
return nil unless self.send("#{name}?".to_sym)
Congo::Grip::Attachment.new({
:name => self["#{name}_name"],
:path => self["#{name}_path"],
:size => self["#{name}_size"],
:content_type => self["#{name}_content_type"],
:body => GridFS::GridStore.read(self.class.database, self["#{name}_path"])
})
end
define_method("#{name}=") do |file|
return if file.nil?
self['_id'] = Mongo::ObjectID.new if _id.blank?
self["#{name}_size"] = file.size rescue File.size(file)
self["#{name}_name"] = file.original_filename rescue File.basename(file.path)
self["#{name}_path"] = configuration[:path].gsub(':class', self.class.to_s.underscore).gsub(':name', self.content_type.name.underscore).gsub(':id', _id.to_s)
self["#{name}_content_type"] = file.content_type rescue MIME::Types.type_for(self["#{name}_name"]).to_s
self.class.attachment_definitions[name] = file
end
define_method("#{name}?") do
!self["#{name}_name"].nil?
end
end
|