【问题标题】:Scope variables/guards范围变量/守卫
【发布时间】:2021-07-10 15:19:14
【问题描述】:

是否有可能有一个变量保证在范围退出时完成。

具体来说,我想要一个守卫:在初始化时调用特定函数,并在范围退出时调用另一个特定函数。

【问题讨论】:

    标签: crystal-lang


    【解决方案1】:

    最好明确地这样做:

    class Guard
      def initialize
        # Init things here
      end
    
      def close
        # clean up things here
      end
    end
    
    def my_method
      guard = Guard.new
      # do things here
    ensure
      guard.close
    end
    

    然后一个常见的模式是使用屈服方法提供更好的接口。在使用外部资源时,您会注意到在标准库中经常看到这一点:

    class Guard
      def self.obtain
        guard = new
        yield guard
      ensure
        guard.close
      end
    
      # ...
    end
    
    Guard.obtain do |guard|
      # do things
    end
    

    当然,如果消费者不应该与它交互,那么产生实际的资源对象是可选的。

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 2015-12-16
      • 2019-10-28
      • 2017-11-27
      • 2013-03-31
      • 2012-04-01
      • 1970-01-01
      • 2020-08-10
      相关资源
      最近更新 更多