Ruby on rails ruby中布尔方法的求值列表

Ruby on rails ruby中布尔方法的求值列表,ruby-on-rails,ruby,ruby-on-rails-4,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?

我有一个方法列表,如果其中任何一个被评估为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
方法,并且我希望每个方法都有不同的消息,我该怎么做呢


我的第一个想法是使用散列,其中键是方法,值是消息或类似的东西。但在这种情况下,短路不起作用,因为所有方法都是事先评估的。我如何才能使这项工作更好、更高效/更优雅?

您的方法可以返回像符号一样真实的值,而不是
true

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\u方法
不仅会返回
true
false
,还会返回一个符号,表示您允许返回可能存储在散列中的消息:

key = parent_method
audit(key) if key
如果我想将自定义消息传递给我的
.audit
方法,并且我想为每个方法传递不同的消息,我该怎么做

您可以使用:


如果不传入任何参数,则始终可以将它们分解为一个简单数组。最简单的例子如下所示:

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
TESTS=[:a?,:b?,:c?]
def parent_方法
失败=测试。查找do |测试|
!发送(测试)
结束
如果(失败)
#failed变量包含失败的方法的名称
#返回'true'。在这里你需要做什么就做什么。

错误你可以遵循类似的模式。在这种情况下,各个验证方法向
errors
对象添加消息。
valid?
方法只是检查是否记录了任何错误消息。您可以让您的
a?
b?
c?
方法填充一个数组,然后您的
父方法检查数组以确定审核是否通过。
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