Skip to content

Instantly share code, notes, and snippets.

@wbailey
Created December 28, 2010 08:27
Show Gist options
  • Save wbailey/757051 to your computer and use it in GitHub Desktop.
Save wbailey/757051 to your computer and use it in GitHub Desktop.
Using a mixin to extend the object instance with the functionality we want
module Logfiles
def name
self.sub(/\.gz$/)
end
def skip?
!(@options[:unzip] && self.gzip?)
end
def gzip?
self.match(/\.gz$/)
end
def cleanup
system "gzip #{self.name}" if self.gzip?
end
end
Dir['*'].each do |file|
file.extend Logfiles
next if file.skip?
IO.foreach(file.name) do |line|
#...
end
file.cleanup
end
@bmarini
Copy link

bmarini commented Dec 28, 2010

Nice example for extending objects. I riffed off your idea and tried to improve it with some custom enumeration.

# Usage:
#
#     LogDir['*'].each do |file|
#        ...
#     end
class LogDir
  module Gzip
    def gunzip
      system "gunzip #{self}" if gzipped?
    end

    def gzip
      system "gzip #{self.gunzipped}" if gzipped?
    end

    def gzipped?
      File.extname(self) == ".gz"
    end

    def gunzipped
      File.basename(self, ".gz")
    end
  end

  def self.[](path)
    new( Dir[path] )
  end

  def initialize(entries)
    @entries = entries.map { |e| e.extend(Gzip) }
  end

  def each
    @entries.each do |entry|
      entry.gunzip
      yield entry.gunzipped
      entry.gzip
    end
  end
end

@wbailey
Copy link
Author

wbailey commented Mar 10, 2011

I like the riff generalization

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment