Sha256: c57d965848ef1c381621d418da9f794028468ed609b09aa0eab1da3e925f3246

Contents?: true

Size: 1.27 KB

Versions: 3

Compression:

Stored size: 1.27 KB

Contents

# frozen_string_literal: true

module GraphqlRails
  # adds `.decorate` class method to any class. Handy when using with paginated responses
  #
  # usage:
  # class FriendDecorator < SimpleDecorator
  #   include GraphqlRails::Decorator
  #
  #   graphql.attribute :full_name
  # end
  #
  # class User
  #   has_many :friends
  #   graphql.attribute :decorated_friends, paginated: true, type: 'FriendDecorator!'
  #
  #   def decorated_friends
  #     FriendDecorator.decorate(friends)
  #   end
  # end
  module Decorator
    require 'active_support/concern'
    require 'graphql_rails/decorator/relation_decorator'

    extend ActiveSupport::Concern

    class_methods do
      def decorate(object, *args, **kwargs)
        if Decorator::RelationDecorator.decorates?(object)
          decorate_with_relation_decorator(object, args, kwargs)
        elsif object.nil?
          nil
        elsif object.is_a?(Array)
          object.map { |item| new(item, *args, **kwargs) }
        else
          new(object, *args, **kwargs)
        end
      end

      private

      def decorate_with_relation_decorator(object, args, kwargs)
        Decorator::RelationDecorator.new(
          relation: object, decorator: self, decorator_args: args, decorator_kwargs: kwargs
        )
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
graphql_rails-3.0.0 lib/graphql_rails/decorator.rb
graphql_rails-2.4.0 lib/graphql_rails/decorator.rb
graphql_rails-2.3.0 lib/graphql_rails/decorator.rb