0

In an attempt to have smaller methods, I'm moving some parts out of a method into smaller private methods. In one private method, however, I'm doing some error handling and would like to break out of the method that called the private method, not just the private method itself. Really basic example, but:

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

How might I break out of the public method entirely and return with those values based on the count, instead of just returning 'No objects' to the public method if that's the case.

Owen Sims
  • 373
  • 3
  • 7

1 Answers1

0

This is a good use of exception handling:

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  
danh
  • 62,181
  • 10
  • 95
  • 136
  • Fair, but that's not substantially different from doing `def public method` `obj = private_method` `return "BlahBlah" if obj.nil?` `end` which is sort of what I'm trying to avoid. I'll be calling a couple different private methods in the public method, and would prefer to keep all the error handling within each private method, just to keep things in tight, related chunks. – Owen Sims Apr 06 '14 at 21:16