Skip to content

Commit

Permalink
Merge pull request #1787 from modosc/allow-callable-prepares
Browse files Browse the repository at this point in the history
support callable prepare objects in Schema::Argument (fixes #1786)
  • Loading branch information
Robert Mosolgo authored Sep 10, 2018
2 parents c4c224f + 434408a commit 50d3b33
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/graphql/schema/argument.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def prepare_value(obj, value)
value
when Symbol, String
obj.public_send(@prepare, value)
when Proc
when ->(p) { p.respond_to? :call }
@prepare.call(value, obj.context)
else
raise "Invalid prepare for #{@owner.name}.name: #{@prepare.inspect}"
Expand Down
27 changes: 27 additions & 0 deletions spec/graphql/schema/argument_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ class Query < GraphQL::Schema::Object

argument :aliased_arg, String, required: false, as: :renamed
argument :prepared_arg, Int, required: false, prepare: :multiply
argument :prepared_by_proc_arg, Int, required: false, prepare: ->(val, context) { context[:multiply_by] * val }

class Multiply
def call(val, context)
context[:multiply_by] * val
end
end

argument :prepared_by_callable_arg, Int, required: false, prepare: Multiply.new
end

def field(**args)
Expand Down Expand Up @@ -93,5 +102,23 @@ class Schema < GraphQL::Schema
# Make sure it's getting the renamed symbol:
assert_equal '{:prepared_arg=>15}', res["data"]["field"]
end
it "calls the method on the provided Proc" do
query_str = <<-GRAPHQL
{ field(preparedByProcArg: 5) }
GRAPHQL

res = SchemaArgumentTest::Schema.execute(query_str, context: {multiply_by: 3})
# Make sure it's getting the renamed symbol:
assert_equal '{:prepared_by_proc_arg=>15}', res["data"]["field"]
end
it "calls the method on the provided callable object" do
query_str = <<-GRAPHQL
{ field(preparedByCallableArg: 5) }
GRAPHQL

res = SchemaArgumentTest::Schema.execute(query_str, context: {multiply_by: 3})
# Make sure it's getting the renamed symbol:
assert_equal '{:prepared_by_callable_arg=>15}', res["data"]["field"]
end
end
end

0 comments on commit 50d3b33

Please sign in to comment.