开发者

Ruby on Rails: passing object with exception from Model

Frankly I know that what stands in the title is probably impossible but I couldn't 开发者_StackOverflow社区come up with something better.

My problem is that I'm not using ActiveRecord to get/save data but some dedicated api via webservice. As such I need to handle some exceptions coming from it (e.g. send mails) but I want to do it in the model to avoid redundancy in the code. By now the only idea that I've come up with is raising exceptions for certain responses from this webservice to generate proper actions in the application controller. Unfortunately one of my actions is to send emails with request and responses from webservice which generated the error. The question is, how can I pass them to the controller?


In general, using exceptions to handle program flow is considered bad practice (but oh so handy! =P).

Instead of trying to explicitly transfer control from the model to the controller, how about passing a block into the model, and using yield to execute that block. In that way, you can have code from the controller being executed in the model, when the model wants it to be run.

hello = "hello"
def func
   goodbye = "goodbye"
   yield
end

func {hello = "world"}

puts goodbye

NameError: undefined local variable or method `goodbye' for #<Object:0x7fa85b7322a0>
    from (irb):25
    from :0

puts hello
"world"

Here's an example of passing code into a function, and showing that this code block can still access variables from the caller (hello == "world" from within the caller's stack space, but was run from inside the function). It feels cleaner to me.

goodbye is there just to show that variables defined within the function get popped off the stack once the function ends.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜