sea*_*ugh 13 ruby ruby-on-rails
我想知道写这样的函数是好还是坏.
def test(x)
if x == 1
return true
else
return "Error: x is not equal to one."
end
end
Run Code Online (Sandbox Code Playgroud)
然后使用它我们做这样的事情:
result = test(1)
if result != true
puts result
end
result = test(2)
if result != true
puts result
end
Run Code Online (Sandbox Code Playgroud)
这只显示第二次测试调用的错误消息.
我正在考虑这样做,因为在一个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...
Run Code Online (Sandbox Code Playgroud)
这样我就不会在控制器中构造错误消息,只是将它们传递给它们,因为我真的不希望控制器关注save_image方法本身做了什么,只是它是否有效.
这对我来说很有意义,但我很好奇这是否被认为是写作方法的好或坏方式.请记住,我在最常见的意义上问这个主要涉及ruby,只是碰巧我在rails项目中这样做,控制器的实际逻辑真的不是我关心的问题.
mik*_*kej 22
我会说在不同情况下返回不同类型(例如布尔与字符串与数字)的方法是一种不好的做法.
如果您有某种测试方法想要返回测试未通过的原因的详细信息,那么您可以返回一对值(a Array
),如下所示:
def test(x)
if x == 1
return true, "x is fine"
else
return false, "Error: x is not equal to one."
end
end
Run Code Online (Sandbox Code Playgroud)
然后将控制器代码的部分写为:
valid, message = @item.save_image(params[:attachment][:file])
if !valid
flash[:notice] = message
redirect_to(new_item_url) and return
end
Run Code Online (Sandbox Code Playgroud)
如果你在谈论一种save_image
方法,它会在大多数时间内成功,但可能会失败,你想表明这种失败和原因,那么我会使用例外,例如
def save_image(file)
raise "No file was specified for saving" if file.nil?
# carry on trying to save image
end
Run Code Online (Sandbox Code Playgroud)
然后你的控制器代码将是:
begin
result = @item.save_image(params[:attachment][:file])
rescue Exception => ex
flash[:notice] = ex.message
redirect_to(new_item_url) and return
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16052 次 |
最近记录: |