【问题标题】:Wrapping array method for cleaner more dry code用于更干净更干代码的包装数组方法
【发布时间】:2021-12-30 05:40:21
【问题描述】:

我正在尝试清理我的代码并找出一种方法来传递数组方法.all?。代码如下:

if <condition>
  parent_1.children.all? {|c| <condition>} ? result_of_true : result_of_false
else
  parent_2.children.all? {|c| <condition>} ? result_of_true : result_of_false
end

他们都使用.all? {|c| &lt;condition&gt;}。我正在尝试得到它,这样我就可以缩短这条线,虽然也许我可以做一些事情,比如为每个孩子创建一个范围并使用它,也许创建一个 proc 并使用它?

我尝试了以下方法:

def new_all?
  proc { |*args| args.all? {|c| c.attribute} }
end

if <condition>
  parent_1.child.new_all? ? result_of_true : result_of_false
else
  parent_2.child.new_all? ? result_of_true : result_of_false
end

# return example: [false, false, true]

或者可能是子类中的某些内容,例如:

def self.new_all?
  all? {|c| <condition>}
end

必须有办法做到这一点。我希望除了必须使用实际的 Array 类之外的东西。

这似乎返回了一个结果数组,但显然不是您期望从 all? 获得的单个布尔值。

更新

我的问题有一些很好的解决方案,其中大部分是我理解并且以前知道的;虽然在我的问题中解释得不好。

@Stefan 在提到 association extensions 时回答了我一直在寻找的问题的答案。我最初尝试实现它并没有成功,但后来开始深入研究 rails scopes 以及它们的功能。能够了解更多关于范围扩展的信息。

【问题讨论】:

  • 什么是result_of_trueresult_of_falsecondition?这些是方法还是变量?在计算它们时,它们是取决于调用块的上下文,还是取决于parentschild
  • child 来自哪里?它是父级的has_many 关联吗?如果是这样,您可以通过association extensions 在代理对象上定义一个方法。 (在这种情况下,它也应该是“孩子”,而不是“孩子”)
  • @Stefan。 Childrenhas_many 关系。关于如何做到这一点的任何建议。我尝试应用association extension 并尝试使用scope。但是,它没有按预期工作。可能是因为我在Object 上使用了Array 方法?
  • @Nappy 你能展示你的尝试吗?

标签: ruby-on-rails ruby


【解决方案1】:

为什么不直接定义一个简单的方法,然后使用一行三进制呢?

def new_all? (x)
 x.all? {|item| <condition>} ? <result of true> : <result of false>
end

<other_condition> ? new_all?(a) : new_all?(b)

【讨论】:

  • 我确实考虑过。想知道是否有更“优雅”的方式。也许没有,这就是答案。
【解决方案2】:

简化(哈哈!)代码的一种简单方法是从条件表达式的分支中提取重复的代码并将其移到条件表达式之外:

if <condition>
  parent_1
else
  parent_2
end.child.all? {|c| <condition>} ? result_of_true : result_of_false

顺便说一句,我发现条件表达式和条件运算符的混合很难阅读。事实上,我发现条件运算符通常很难阅读。在 Ruby 中也完全没有必要。 C 中需要条件运算符,因为它是一个运算符,因此是一个表达式,而条件语句是一个语句。但在 Ruby 中,条件表达式已经是表达式,所以不需要条件运算符。

所以,我可能会这样写:

if if condition
     parent_1
   else
     parent_2
   end.child.all? { |c| condition }
  result_of_true
else
  result_of_false
end

或许

if if condition then parent_1 else parent_2 end.child.all? { |c| condition }
  result_of_true
else
  result_of_false
end

但是,这需要将一些东西提取到方法或至少变量中。

【讨论】:

  • 虽然if if 在逻辑上和句法上都是正确的,但在很多方面让我感到不舒服:)
猜你喜欢
  • 1970-01-01
  • 2013-12-27
  • 2022-09-25
  • 1970-01-01
  • 2020-05-23
  • 2022-08-13
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多