Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

cleaning up. refactoring how attachments are created and called.

  • Loading branch information...
commit 920ae494aa9500bee4d4cbd4bfbb4dad68d34eaa 1 parent 58a61a4
@twoism authored
Showing with 18 additions and 11 deletions.
  1. +11 −5 lib/grip/attachment.rb
  2. +7 −6 lib/grip/has_attachment.rb
View
16 lib/grip/attachment.rb
@@ -3,8 +3,13 @@ module Grip
class Attachment
include MongoMapper::Document
- belongs_to :owner, :polymorphic => true
- many :attached_variants, :as => :owner, :class_name => "MongoMapper::Grip::Attachment", :dependent => :destroy
+ belongs_to :owner,
+ :polymorphic => true
+
+ many :attached_variants,
+ :as => :owner,
+ :class_name => "MongoMapper::Grip::Attachment",
+ :dependent => :destroy
key :owner_id, ObjectId, :required => true
key :owner_type, String, :required => true
@@ -15,8 +20,8 @@ class Attachment
key :content_type, String
key :variants, Hash
- after_save :build_variants
- before_destroy :destroy_file
+ after_save :build_variants
+ before_destroy :destroy_file
def file=new_file
raise InvalidFile unless (new_file.is_a?(File) || new_file.is_a?(Tempfile))
@@ -47,10 +52,11 @@ def build_variants
self.variants.each do |variant, dimensions|
self.class.create_method variant.to_sym do
- Attachment.find_or_initialize_by_name_and_owner_id("#{variant.to_s}",self._id)
+ attached_variants.find_or_create_by_name(:name=>"#{variant.to_s}")
end
self.class.create_method "#{variant}=".to_sym do |file_hash|
+
new_attachment = Attachment.find_or_initialize_by_name_and_owner_id("#{variant.to_s}",self._id)
new_attachment.owner_type = self.class.to_s
new_attachment.file_name = File.basename(file_hash[:uploaded_file].path)
View
13 lib/grip/has_attachment.rb
@@ -13,11 +13,11 @@ def has_grid_attachment name, opts={}
define_method("#{name}=") do |new_file|
raise InvalidFile unless (new_file.is_a?(File) || new_file.is_a?(Tempfile))
-
+
+ self.class.uploaded_files[name][:file] = new_file
self['_id'] = Mongo::ObjectID.new if _id.blank?
- new_attachment = Attachment.find_or_initialize_by_name_and_owner_id(name.to_s,self._id)
+ new_attachment = attachments.find_or_create_by_name(name.to_s)
update_attachment_attributes!(new_attachment, new_file, opts)
- self.class.uploaded_files[name][:file] = new_file
end
end
@@ -31,8 +31,10 @@ def self.included(base)
base.extend ClassMethods
base.class_eval do
after_save :save_attachments
-
- many :attachments, :as => :owner, :class_name => "MongoMapper::Grip::Attachment", :dependent => :destroy
+ many :attachments,
+ :as => :owner,
+ :class_name => "MongoMapper::Grip::Attachment",
+ :dependent => :destroy
end
end
@@ -70,7 +72,6 @@ def create_variant attachment, variant, dimensions
end
file_hash = {:resized_file => tmp,:uploaded_file => tmp_file}
-
attachment.send("#{variant}=", file_hash)
end
Please sign in to comment.
Something went wrong with that request. Please try again.