Ruby: Destructors?

前端 未结 6 1964
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 04:26

I need to occasionaly create images with rmagick in a cache dir.

To then get rid of them fast, without loosing them for the view, I want to delete the image-files wh

6条回答
  •  有刺的猬
    2020-11-30 04:46

    GC quirks are nice to read about, but why not properly deallocate resources according to already existing language syntax?

    Let me clarify that.

    class ImageDoer
      def do_thing(&block)
        image= ImageMagick.open_the_image # creates resource
        begin
          yield image # yield execution to block
        rescue
          # handle exception
        ensure
          image.destruct_sequence # definitely deallocates resource
        end
      end
    end
    
    doer= ImageDoer.new
    doer.do_thing do |image|
      do_stuff_with_image # destruct sequence called if this throws
    end # destruct_sequence called if execution reaches this point
    

    Image is destroyed after the block finishes executing. Just start a block, do all the image processing inside, then let the image destroy itself. This is analogous to the following C++ example:

    struct Image
    {
      Image(){ /* open the image */ }
      void do_thing(){ /* do stuff with image */ }
      ~Image(){ /* destruct sequence */ }
    };
    
    int main()
    {
      Image img;
      img.do_thing(); // if do_thing throws, img goes out of scope and ~Image() is called
    } // special function ~Image() called automatically here
    

提交回复
热议问题