加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Ruby中返回true或者错误消息

发布时间:2020-12-16 21:43:30 所属栏目:百科 来源:网络整理
导读:我想知道这样的写作功能是否被认为是好还是坏. def test(x) if x == 1 return true else return "Error: x is not equal to one." endend 然后使用它,我们做这样的事情: result = test(1)if result != true puts resultendresult = test(2)if result != tru
我想知道这样的写作功能是否被认为是好还是坏.
def test(x)
    if x == 1
        return true
    else
        return "Error: x is not equal to one."
    end
end

然后使用它,我们做这样的事情:

result = test(1)

if result != true
    puts result
end

result = test(2)

if result != true
    puts result
end

其中只显示第二个测试调用的错误消息.

我正在考虑这样做,因为在我在控制器代码里面的rails项目中,我调用了一个模型的实例方法,如果出现了问题,我希望模型将错误消息返回给控制器,并且控制器错误消息并将其放入闪存并重定向.喜欢这样的喜欢

def create
    @item = Item.new(params[:item])

    if !@item.nil?
        result = @item.save_image(params[:attachment][:file])

        if result != true
            flash[:notice] = result

            redirect_to(new_item_url) and return
        end

        #and so on...

这样我就不会在控制器中构建错误消息,只是传递给它们,因为我真的不希望控制器关心save_image方法本身是否有效.

这对我来说是有意义的,但我很好奇,这是否被认为是一种好的或坏的写作方法.请记住,我在最通常的意义上问这个问题,主要是关于ruby,只是发生在我在rails项目中这样做的时候,控制器的实际逻辑真的不是我的关心.

解决方法

我会说,在不同情况下返回不同类型(例如布尔对字符串与数字)的方法是不好的做法.

如果您有某种测试方法希望返回测试未通过的详细信息,那么您可以返回一对值(Array),如下所示:

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

然后将控制器代码的部分写为:

valid,message = @item.save_image(params[:attachment][:file])

if !valid
  flash[:notice] = message
  redirect_to(new_item_url) and return
end

如果你正在谈论一个save_image方法,在大多数时候都会成功,但是可能会失败,你想指出这个失败,然后我会用exceptions例如

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

然后您的控制器代码将符合以下条件:

begin
  result = @item.save_image(params[:attachment][:file])
rescue Exception => ex
  flash[:notice] = ex.message
  redirect_to(new_item_url) and return
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读