Sha256: bfdfee9063edf257779c42bf92fd8e18e9b3e9b40b3d2c393795d51cbb8c99fd

Contents?: true

Size: 1.45 KB

Versions: 15

Compression:

Stored size: 1.45 KB

Contents

class Condenser
  module Utils

    # Public: Write to a file atomically. Useful for situations where you
    # don't want other processes or threads to see half-written files.
    #
    #   Utils.atomic_write('important.file') do |file|
    #     file.write('hello')
    #   end
    #
    # Returns nothing.
    def self.atomic_write(filename)
      dirname, basename = File.split(filename)
      basename = [
        basename,
        Thread.current.object_id,
        Process.pid,
        rand(1000000)
      ].join('.'.freeze)
      tmpname = File.join(dirname, basename)

      File.open(tmpname, 'wb+') do |f|
        yield f
      end

      File.rename(tmpname, filename)
    ensure
      File.delete(tmpname) if File.exist?(tmpname)
    end
    
    # Internal: Inject into target module for the duration of the block.
    #
    # mod - Module
    #
    # Returns result of block.
    def self.module_include(base, mod)
      old_methods = {}

      mod.instance_methods.each do |sym|
        old_methods[sym] = base.instance_method(sym) if base.method_defined?(sym)
      end

      mod.instance_methods.each do |sym|
        method = mod.instance_method(sym)
        base.send(:define_method, sym, method)
      end

      yield
    ensure
      mod.instance_methods.each do |sym|
        base.send(:undef_method, sym) if base.method_defined?(sym)
      end
      old_methods.each do |sym, method|
        base.send(:define_method, sym, method)
      end
    end
    
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
condenser-1.4 lib/condenser/utils.rb
condenser-1.3 lib/condenser/utils.rb
condenser-1.2 lib/condenser/utils.rb
condenser-1.0 lib/condenser/utils.rb
condenser-1.0.rc1 lib/condenser/utils.rb
condenser-0.3 lib/condenser/utils.rb
condenser-0.2 lib/condenser/utils.rb
condenser-0.1 lib/condenser/utils.rb
condenser-0.0.12 lib/condenser/utils.rb
condenser-0.0.11 lib/condenser/utils.rb
condenser-0.0.10 lib/condenser/utils.rb
condenser-0.0.9 lib/condenser/utils.rb
condenser-0.0.8 lib/condenser/utils.rb
condenser-0.0.7 lib/condenser/utils.rb
condenser-0.0.5 lib/condenser/utils.rb