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

#downloadvoid

This method returns an undefined value.

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



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

def download
  render_raw_image(disposition: "attachment")
end

#originalvoid

This method returns an undefined value.

Renders the original image data, without any processing.



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

def original
  render_raw_image
end

#requested_sizeVector2d

Returns the requested size as a vector.

Returns:

  • the size from the URL



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

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

#showvoid

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.



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

def show
  render_image(format: requested_format)
end

#uncroppedvoid

This method returns an undefined value.

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



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

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