Module: Grip::HasAttachment::InstanceMethods

Defined in:
lib/grip/has_attachment.rb

Instance Method Summary collapse

Instance Method Details

#create_variant(attachment, variant, dimensions) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/grip/has_attachment.rb', line 75

def create_variant attachment, variant, dimensions
  return if uploaded_files[attachment.name.to_sym].nil?
  tmp_file = uploaded_files[attachment.name.to_sym][:file]
  begin
    tmp   = Tempfile.new("#{attachment.name}_#{variant}")
    image = Miso::Image.new(tmp_file.path)

    image.crop(dimensions[:width], dimensions[:height])  if dimensions[:crop]
    image.fit(dimensions[:width], dimensions[:height])   unless dimensions[:crop]

    image.write(tmp.path)
  rescue RuntimeError => e
    warn "Image was not resized. #{e}"
    tmp = tmp_file
  end

  file_hash = {:resized_file => tmp, :uploaded_file => tmp_file}
  attachment.send("#{variant}=", file_hash)
end

#save_attachmentsObject



67
68
69
70
71
72
73
# File 'lib/grip/has_attachment.rb', line 67

def save_attachments
  attachments.each do |attachment|
    attachment.variants.each do |variant, dimensions|
      create_variant(attachment, variant, dimensions)
    end
  end
end

#update_attachment_attributes!(new_attachment, new_file, opts) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/grip/has_attachment.rb', line 54

def update_attachment_attributes! new_attachment, new_file, opts
  new_attachment.owner_type   = self.class.to_s
  new_attachment.file_name    = File.basename(new_file.path)
  new_attachment.file_size    = File.size(new_file.path)
  
  # ruby 1.9 mime type hack
  new_attachment.content_type = MIME::Types.type_for(new_file.path)[0].content_type rescue MIME::Types.type_for(new_file.path)
  
  new_attachment.file         = new_file
  new_attachment.variants     = opts[:variants] || {}
  new_attachment.save!
end

#uploaded_filesObject



50
51
52
# File 'lib/grip/has_attachment.rb', line 50

def uploaded_files
  @uploaded_files ||= {}
end