Module: DynamicImage::Controller

Extended by:
ActiveSupport::Concern
Includes:
Dis::Controller
Defined in:
lib/dynamic_image/controller.rb

Overview

DynamicImage Controller

Serves images. Include it in a controller and define a model method returning the class to serve, then declare the routes with Routing#image_resources.

class ImagesController < ApplicationController
include DynamicImage::Controller

private

def model
  Image
end
end

Generating images is expensive, so every request must be signed with an HMAC digest. This protects against denial of service attacks and URL enumeration. The helpers in Helper sign the URLs they build.

Responses are cached for a year and answer If-Modified-Since. The URL carries a timestamp, so a changed image is a changed URL.

See Also:

Constant Summary collapse

PROCESSED_FORMATS =

Formats show and uncropped will render.

%i[gif jpeg jpg jxl png tiff webp].freeze
STORED_FORMATS =

Additional formats original and download will serve.

(PROCESSED_FORMATS + %i[avif heic]).freeze

Instance Method Summary collapse

Instance Method Details

#download ⇒ void

This method returns an undefined value.

Same as original, but served as an attachment so the browser downloads the file rather than displaying it.



71
72
73
# File 'lib/dynamic_image/controller.rb', line 71

def download
  render_raw_image(disposition: "attachment")
end

#original ⇒ void

This method returns an undefined value.

Renders the original image data, without any processing.



64
65
66
# File 'lib/dynamic_image/controller.rb', line 64

def original
  render_raw_image
end

#requested_size ⇒ Vector2d

Returns the requested size as a vector.

Returns:

  • (Vector2d) —

    the size from the URL



78
79
80
# File 'lib/dynamic_image/controller.rb', line 78

def requested_size
  Vector2d.parse(params[:size])
end

#show ⇒ void

This method returns an undefined value.

Renders the image, cropped and resized to the requested size.

Responds to the image formats, and to HTML with a page showing the image and its metadata.



50
51
52
# File 'lib/dynamic_image/controller.rb', line 50

def show
  render_image(format: requested_format)
end

#uncropped ⇒ void

This method returns an undefined value.

Same as show, but renders the image without any pre-cropping applied.



57
58
59
# File 'lib/dynamic_image/controller.rb', line 57

def uncropped
  render_image(format: requested_format, uncropped: true)
end