Where are catch and throw useful in Ruby?

前端 未结 4 624
囚心锁ツ
囚心锁ツ 2021-01-17 19:20

I really don\'t see a sane use for these. There is already rescue and raise, so why the need for throw and catch? It seem

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-17 19:38

    They can be really useful in simplifying DSLs for end users by passing control out of the DSL without the need for complex case / if statements

    I have a Ruby app which allows users to extend it via an internal DSL. Some of the functions in the DSL need to return control to specific parts of my application. Let's take a simple example. Suppose the user is developing a simple extension concerning dates

    if today is a holiday then
       do nothing
    end
    
    week_of_year = today.week.number
    
    if week_of_year < 10 then
    
    ...
    

    The do nothing bit triggers a throw which passes control out of the exec statement and back to me.

    Rather than continuing to execute the DSL, on some condition, we want it to exit and hand control back to my application. Now you could get the user to use lots of embedded if statements and have the DSL end naturally but that just obscures what the logic is trying to say.

    Throw really is a goto which is 'considered dangerous' but damn it sometimes they are the best solution.

提交回复
热议问题