Module: Imagery::Core

Included in:
Imagery
Defined in:
lib/imagery.rb

Overview

In order to facilitate a plugin architecture, all overridable methods are placed in the ‘Core` module. Imagery::S3 demonstrates overriding in action.

Instance Method Summary collapse

Instance Method Details

#deleteObject

A very simple and destructive method. Deletes the entire folder for the current prefix/id combination.



96
97
98
99
100
# File 'lib/imagery.rb', line 96

def delete
  return if not id

  FileUtils.rm_rf(root)
end

#initialize(prefix, id = nil, sizes = {}) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/imagery.rb', line 31

def initialize(prefix, id = nil, sizes = {})
  @prefix   = prefix.to_s
  @id       = id.to_s if id
  @sizes    = sizes
  @original = :original      # Used as the filename for the raw image.
  @ext      = :jpg           # We default to jpg for the image format.
end

#save(io, id = nil) ⇒ Object

Accepts an ‘IO` object, typically taken from an input.

The second optional ‘id` argument is used when you want to force a new resource, useful in conjunction with cloudfront / high cache scenarios where updating an existing image won’t suffice.

Examples:

# Let's say we're in the context of a Sinatra handler,
# and a file was submitted to params[:file]

post "upload" do
  im = Imagery.new(:avatar, current_user.id, thumb: ["20x20"])
  im.save(params[:file][:tempfile])

  # At this point we have two files, original.jpg and thumb.jpg

  { original: im.url, thumb: im.url(:thumb) }.to_json
end


67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/imagery.rb', line 67

def save(io, id = nil)
  GM.identify(io) or raise(InvalidImage)

  # We delete the existing object iff:
  # 1. An id was passed
  # 2. We have an existing id already.
  # 3. The id passed is different from the existing id.
  delete if id && self.id && id != self.id

  # Now we can assign the new id passed, with the assurance that the
  # old id has been deleted and won't be used anymore.
  @id = id.to_s if id

  # Ensure that the path to all images is created.
  FileUtils.mkdir_p(root)

  # Write the original filename as binary using the `IO` object's data.
  File.open(root(ext(@original)), "wb") { |file| file.write(io.read) }

  # We resize the original raw image to different sizes which we
  # defined in the constructor. GraphicsMagick is assumed to exist
  # within the machine.
  sizes.each do |size, (resize, extent)|
    GM.convert root(ext(@original)), root(ext(size)), resize, extent
  end
end

#url(file = @original) ⇒ Object

Returns the url for a given size, which defaults to ‘:original`.

If the id is nil, a missing path is returned.



42
43
44
45
46
# File 'lib/imagery.rb', line 42

def url(file = @original)
  return "/missing/#{prefix}/#{ext(file)}" if id.to_s.empty?

  "/#{prefix}/#{id}/#{ext(file)}"
end