Returning true or error message in Ruby

后端 未结 1 849
眼角桃花
眼角桃花 2021-01-04 03:33

I\'m wondering if writing functions like this is considered good or bad form.

def test(x)
    if x == 1
        return true
    else
        return \"Error:          


        
相关标签:
1条回答
  • 2021-01-04 04:14

    I would say that methods that return different types (e.g. boolean vs. string vs. numbers) under different circumstances are a bad practice.

    If you have some sort of test method that wants to return details of why the test has not passed then you can return a pair of values (an Array) as follows:

    def test(x)
        if x == 1
            return true, "x is fine"
        else
            return false, "Error: x is not equal to one."
        end
    end
    

    and then write the section of your controller code as:

    valid, message = @item.save_image(params[:attachment][:file])
    
    if !valid
      flash[:notice] = message
      redirect_to(new_item_url) and return
    end
    

    If you're talking about a save_image method that will succeed the majority of the time but may fail and you want to indicate this failure and the reason then I would use exceptions e.g.

    def save_image(file)
      raise "No file was specified for saving" if file.nil? 
      # carry on trying to save image
    end
    

    and then your controller code would be along the lines of:

    begin
      result = @item.save_image(params[:attachment][:file])
    rescue Exception => ex
      flash[:notice] = ex.message
      redirect_to(new_item_url) and return
    end
    
    0 讨论(0)
提交回复
热议问题