Skip to content

Instantly share code, notes, and snippets.

@bibendi
Last active September 15, 2020 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bibendi/e90de02cc282b8bf305fa4b2f71be405 to your computer and use it in GitHub Desktop.
Save bibendi/e90de02cc282b8bf305fa4b2f71be405 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
module CoreBy
module FieldExtensions
# GraphQL field extension allows returning URL of Active Storage attachment.
# TODO: Move to `graphql-field_attachment` gem?
class AttachmentUrlField < GraphQL::Schema::FieldExtension
attr_reader :attachment_assoc
def apply
attachment = options.fetch(:attachment) { field.original_name.to_s.sub(/_url$/, "") }
@attachment_assoc = "#{attachment}_attachment"
if (variant = options[:variant])
field.argument(
:variant,
variant.fetch(:enum),
required: variant.fetch(:required),
description: "Attachment variant"
)
end
end
def resolve(object:, arguments:, **rest)
object.preload_association(attachment_assoc => :blob)
end
def after_resolve(value:, arguments:, object:, **rest)
return if value.nil?
return value if value.is_a?(GraphQL::Execution::Interpreter::RawValue)
CoreBy::ActiveStorage.attachment_url(value, variant: arguments[:variant]&.to_sym)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment