ruby - 在 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,无法记住要谷歌搜索的内容。
解决方案
您可以尝试定义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
推荐阅读
- reactjs - 设置状态时如何将方法应用于字符串,反应钩子
- python-3.x - PyQt5让QDialog在允许用户输入之前等待进程完成
- sorting - DAX Related() 与 Power BI 中的多对多关系
- c# - 使用 .net 核心 json 模型绑定在无效 json 上引发 json 验证错误
- android - android内部的功能标志功能?
- html - HTML选取框需要等待其他完成才能开始滚动
- r - 在R中创建具有相同距离的随机数序列
- mysql - 哪里存在减慢查询
- reactjs - Codesandbox 无效的钩子
- aws-glue - llvmlite-0.31.0 - OSError:无法加载共享对象文件:libllvmlite.so