Ruby: Destructors?

前端 未结 6 1984
伪装坚强ぢ
伪装坚强ぢ 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:48

    There is very simple solution for your problem. Ruby design encourage you to do all actions in definite and clear way. No need for magic actions in constructor/destructor. Yes, constructors are required as a convenient way to assign initial state of object but not for "magic" actions. Let me illustrate this approach on possible solution. Goal, to keep image objects available but clean cache files of images.

    # you are welcome to keep an in memory copy of the image
    # GC will take care of it.
    class MyImage
      RawPNG data
    end
    
    # this is a worker that does operations on the file in cache directory.
    # It knows presizely when the file can be removed (generate_image_final)
    # no need to wait for destructor ;)
    class MyImageGenerator
      MyImage @img
    
      def generate_image_step1
        @image_file = ImageLib.create_file
      end
      def generate_image_step2
        ImageLib.draw @image_file
      end
      def generate_image_final
        @img=ImageLib.load_image @image_file
        delete_that_file @image_file
      end
    
      def getImage
        # optional check image was generated
        return @img
      end
    end
    

提交回复
热议问题