Module: Grip::HasAttachment::InstanceMethods

Defined in:
lib/grip/has_attachment.rb

Instance Method Summary collapse

Instance Method Details

#create_variant(attachment, variant, dimensions) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/grip/has_attachment.rb', line 63

def create_variant attachment, variant, dimensions
  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



55
56
57
58
59
60
61
# File 'lib/grip/has_attachment.rb', line 55

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



45
46
47
48
49
50
51
52
53
# File 'lib/grip/has_attachment.rb', line 45

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)
  new_attachment.content_type = MIME::Types.type_for(new_file.path)
  new_attachment.file         = new_file
  new_attachment.variants     = opts[:variants] || {}
  new_attachment.save!
end

#uploaded_filesObject



42
43
44
# File 'lib/grip/has_attachment.rb', line 42

def uploaded_files
  @uploaded_files ||= {}
end