1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
# frozen_string_literal: true
module Graphql
class Arguments
delegate :blank?, :empty?, to: :to_h
def initialize(values)
@values = values
end
def to_h
@values
end
def ==(other)
to_h == other&.to_h
end
alias_method :eql, :==
def to_s
return '' if empty?
@values.map do |name, value|
value_str = as_graphql_literal(value)
"#{GraphqlHelpers.fieldnamerize(name.to_s)}: #{value_str}"
end.join(", ")
end
def as_graphql_literal(value)
self.class.as_graphql_literal(value)
end
# Transform values to GraphQL literal arguments.
# Use symbol for Enum values
def self.as_graphql_literal(value)
case value
when ::Graphql::Arguments then "{#{value}}"
when Array then "[#{value.map { |v| as_graphql_literal(v) }.join(',')}]"
when Hash then "{#{new(value)}}"
when Integer, Float, Symbol then value.to_s
when String, GlobalID then "\"#{value.to_s.gsub(/"/, '\\"')}\""
when Time, Date then "\"#{value.iso8601}\""
when NilClass then 'null'
when true then 'true'
when false then 'false'
else
value.to_graphql_value
end
rescue NoMethodError
raise ArgumentError, "Cannot represent #{value} (instance of #{value.class}) as GraphQL literal"
end
def merge(other)
self.class.new(@values.merge(other.to_h))
end
def +(other)
if blank?
other
elsif other.blank?
self
elsif other.is_a?(String)
[to_s, other].compact.join(', ')
else
merge(other)
end
end
end
end
|