返回调用私有方法的方法

时间:2014-04-06 20:51:19

标签: ruby return private-methods

为了尝试使用更小的方法,我将一些方法从一个方法转移到更小的私有方法中。但是,在一个私有方法中,我正在进行一些错误处理,并希望打破调用私有方法的方法,而不仅仅是私有方法本身。真的是基本的例子,但是:

def public method
  private_method

  # Do other stuff based on the results of that private method
end

private

def private method
  objects = Object.where('something')
  return 'No objects' if objects.count == 0
  return 'Less than 3 objects' if objects.count < 3
  objects
end

我怎样才能彻底摆脱公共方法,并根据计数返回这些值,而不仅仅是返回&#39;没有对象&#39;对于公共方法,如果是这样的话。

1 个答案:

答案 0 :(得分:0)

这很好地使用了异常处理:

def public_method 
  begin  
    private_method 
  rescue  
    return "BlahBlah"
  end  
  # Do other stuff based on the results of that private method 
end  

private

def private_method 
  object = Object.find(1)
  raise "not found" if object.nil?
  object
end