首页 > 解决方案 > 在 GraphQL 突变中干燥多个 lambda 的正确方法

问题描述

我正在尝试使用一堆做同样事情的 lambda,并通过将它们分解为一个方法来干燥它们。有问题的代码在模块/类中,我忘记了正确的方法:/

文档显示了一个使用 lambda 的示例 -

module Mutations
  class MyMutation < BaseMutation
    argument :name, String, required: true, prepare: -> (value, ctx) { value.strip! }
  end
end

我试过了 -

module Mutations
  class MyMutation < BaseMutation
    argument :name, String, required: true, prepare: :no_whitespace

    def no_whitespace(value)
      value.strip!
    end
  end
end

但是在类错误中找不到方法。

我也尝试将它移动到它自己的模块或类 -

module Mutations
  class MyMutation < BaseMutation
    argument :name, String, required: true, prepare: Testing::no_whitespace
  end

  class Testing
    def no_whitespace(value)
      value.strip!
    end
  end 
end

我知道这很愚蠢,但我找不到正确的组合来让它发挥作用,而且我的大脑已经忘记了太多 Ruby,无法记住要谷歌搜索的内容。

标签: rubygraphqlgraphql-ruby

解决方案


您可以尝试定义no_whitespace为模块方法,例如

class Testing
  # since the example shows 2 arguments you need to be able 
  # to accept both even if you only use 1
  def self.no_whitespace(value,*_)
    value.strip!
  end
end 

然后使用

class MyMutation < BaseMutation
  argument :name, String, required: true, prepare: Testing.method(:no_whitespace)
end

Testing.method(:no_whitespace)将返回一个Method在大多数情况下会非常像 lambda 的行为。

然而,如果

module Mutations
  class MyMutation < BaseMutation
    argument :name, String, required: true, prepare: :no_whitespace

    def no_whitespace(value)
      value.strip!
    end
  end
end

返回一个NoMethodError: undefined method no_whitespace' for MyMutation:Class然后尝试将其定义为类实例方法,看看会发生什么:

def self.no_whitespace(value)
  value.strip!
end 

推荐阅读