评估布尔方法列表ruby

时间:2017-11-17 18:37:39

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个方法列表,如果其中任何一个评估为true,我必须触发对模型的操作,在这种情况下是模型审计。

例如:

def a?
  false # in reality this is some code
end

def b?
  true # in reality this is some code
end

def c?
  true # in reality this is some code
end

现在我可以将其分组为像父方法一样:

def parent_method
  a? || b? || c?
end

这会使代码短路,而c?永远不会被执行,这是伟大的。我可以执行我的.audit方法。

但是,如果我想将自定义消息传递给我的.audit方法,并且我希望每种方法都有不同的消息,我该怎么做?

我的第一个虽然有一个哈希,键是方法和值是消息或沿着该行的东西。但在这种情况下,短路不起作用,因为所有方法都是事先评估的。如何让这项工作更好,更有效/更优雅?

3 个答案:

答案 0 :(得分:1)

而不是true您的方法可以像符号一样返回 trueish 值。

def a?
  false # in reality this is some code
end

def b?
  :b # in reality this is some code
end

def c?
  :c # in reality this is some code
end

您仍然允许在

中使代码短路
def parent_method
  a? || b? || c?
end

但现在parent_method不仅会返回truefalse,而且会返回一个符号,表示您允许返回可能存储在哈希中的消息:

key = parent_method
audit(key) if key

答案 1 :(得分:1)

如果你没有传递任何参数,你总是可以将它们分解成一个简单的数组。最小的例子如下:

TESTS = [ :a?, :b?, :c? ]

def parent_method
  failed = TESTS.find do |test|
    !send(test)
  end

  if (failed)
    # The failed variable contains the name of the method that failed
    # to return `true`. Do whatever you need to do here.
    errors << "Test #{failed} returned false!"

    false
  else
    true
  end
end

答案 2 :(得分:0)

  

如果我想将自定义消息传递给我的.audit方法,并且我希望每种方法都有不同的消息,我该怎么做?

您可以使用case expression

case
when a? then audit(:a)
when b? then audit(:b)
when c? then audit(:c)
end
相关问题