Skip to content

Instantly share code, notes, and snippets.

@vilusa
Last active December 29, 2020 09:18
Show Gist options
  • Save vilusa/e4649d0bb5cf31a04e174338f930cc28 to your computer and use it in GitHub Desktop.
Save vilusa/e4649d0bb5cf31a04e174338f930cc28 to your computer and use it in GitHub Desktop.
ActiveStorage::Util
module ActiveStorage
module Util
class << self
def image(resource, **options)
return '/no_image.png' unless resource.attached?
size = handle_size?(options)
return resource.service_url unless size
resource.variant(resize_to_fill: size).processed.service_url
end
private
def handle_size?(options)
if options[:width].present? || options[:height].present?
raise Errors::NotImplemented, 'Wrong parameters' if !options[:width].present? || !options[:height].present?
return [options[:width], options[:height]]
end
return size(options[:size]) if options[:size].present?
false
end
def size(size)
size = size.to_sym if size.is_a?(String)
case size
when :thumb
[100, '100>']
when :square
[200, '200>']
when :medium
[300, '300>']
else
raise NotImplementedError
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment