【问题标题】:Proper way to DRY up multiple lambdas in a GraphQL mutation在 GraphQL 突变中干燥多个 lambda 的正确方法
【发布时间】:2019-09-26 07:27:21
【问题描述】:

我正在尝试使用一堆做同样事情的 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,以至于无法记住要谷歌搜索的内容。

【问题讨论】:

    标签: ruby graphql graphql-ruby


    【解决方案1】:

    您可以尝试将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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 2020-04-23
      • 2021-08-22
      • 2020-12-12
      • 1970-01-01
      • 2014-01-15
      • 2017-10-25
      相关资源
      最近更新 更多