Skip to content

Instantly share code, notes, and snippets.

@dorianmariecom
Created November 24, 2021 19:56
Show Gist options
  • Select an option

  • Save dorianmariecom/1fca34b0402cf0facd1cbbcd2b9ebb34 to your computer and use it in GitHub Desktop.

Select an option

Save dorianmariecom/1fca34b0402cf0facd1cbbcd2b9ebb34 to your computer and use it in GitHub Desktop.
module RenderJpgConcern
MIN_WIDTH = 20
MAX_WIDTH = 1000
MIN_HEIGHT = 20
MAX_HEIGHT = 1000
DEFAULT_WIDTH = 400
DEFAULT_HEIGHT = 300
def render_jpg(model)
http_cache_forever(public: true) do
image = model.image
return render_blank_jpg unless image.attached?
width = params.dig(:image, :width).presence
height = params.dig(:image, :height).presence
options = { format: :jpg, gravity: :center }
if width || height
width ||= DEFAULT_WIDTH
height ||= DEFAULT_HEIGHT
width = [MAX_WIDTH, [MIN_WIDTH, width.to_i].max].min
height = [MAX_HEIGHT, [MIN_HEIGHT, height.to_i].max].min
options[:resize] = "#{width.to_i}x#{height.to_i}^"
options[:extent] = "#{width.to_i}x#{height.to_i}"
end
send_data(
image.variant(**options).processed.download,
filename: "#{model.slug}.jpg",
disposition: :inline,
type: "image/jpeg"
)
end
rescue ActiveStorage::FileNotFoundError
model.image.purge
render_blank_jpg
end
def render_blank_jpg
send_file(
Rails.root.join("app/assets/images/blank.jpg"),
filename: "blank.jpg",
disposition: :inline,
type: "image/jpeg"
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment