@@ -99,22 +99,32 @@ def self.interpolate_variables(query, variables = {})
99
99
end
100
100
101
101
def self . interpolate_variables! ( query , variables = { } )
102
- variables . each do |variable , value |
103
- case value
104
- when Integer , Float , TrueClass , FalseClass
105
- # These types are safe to directly interpolate into the query, and GraphQL does not expect these types to be quoted.
106
- query . gsub! ( "$#{ variable . to_s } " , value . to_s )
107
- else
108
- # A string is either a GraphQL String or ID type.
109
- # This means we need to
110
- # a) Surround the value in quotes
111
- # b) escape special characters in the string
112
- #
113
- # This else also catches unknown objects, which could break the query if we directly interpolate.
114
- # These objects get converted to strings, then escaped.
115
-
116
- query . gsub! ( "$#{ variable . to_s } " , value . to_s . inspect )
117
- end
102
+ variables . each { |variable , value | query . gsub! ( "$#{ variable . to_s } " , stringify_variable ( value ) ) }
103
+ end
104
+
105
+ def self . stringify_variable ( value )
106
+ case value
107
+ when Integer , Float , TrueClass , FalseClass
108
+ # These types are safe to directly interpolate into the query, and GraphQL does not expect these types to be quoted.
109
+ value . to_s
110
+ when Array
111
+ # Arrays can contain elements with various types, so we need to check them one by one
112
+ stringified_elements = value . map { |element | stringify_variable ( element ) }
113
+ "[#{ stringified_elements . join ( ', ' ) } ]"
114
+ when Hash
115
+ # Hashes can contain values with various types, so we need to check them one by one
116
+ stringified_key_value_pairs = value . map { |key , value | "#{ key } : #{ stringify_variable ( value ) } " }
117
+ "{#{ stringified_key_value_pairs . join ( ', ' ) } }"
118
+ else
119
+ # A string is either a GraphQL String or ID type.
120
+ # This means we need to
121
+ # a) Surround the value in quotes
122
+ # b) escape special characters in the string
123
+ #
124
+ # This else also catches unknown objects, which could break the query if we directly interpolate.
125
+ # These objects get converted to strings, then escaped.
126
+
127
+ value . to_s . inspect
118
128
end
119
129
end
120
130
0 commit comments