Browse | Submit A New Snippet | Create A Package

 

Core Class Extensions

Type:
Function
Category:
File Management
License:
GNU Library Public License
Language:
Ruby
 
Description:
All the stuff I've wanted and had to add to Ruby's infrastructure that I've remembered to save.

Versions Of This Snippet::

James Schneider
Snippet ID Download Version Date Posted Author Delete
3790.12008-08-27 20:35James Schneider

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :0.1

require "find"
require "fileutils"

class String
 def left(chars)
  chars > 0 ? self[0,chars] : self[0,self.length+chars]
 end
 def right(chars)
  chars > 0 ? self[self.length-chars..-1] : self[-chars..-1]
 end
 def matchEvery(someRegexp)
  matches = []
  matchOn = self
  while matchOn =~ someRegexp
   matches << $~.to_a
   matchOn = $' #' Match again on the portion of the string after the match.
  end
  return matches
 end
end

module Find
 def self.findWithin(path)
  if File.directory?(path)
   handledDirectoryEntry = false
   find(path){|subPath|
    if not handledDirectoryEntry
     handledDirectoryEntry = true
    else
     yield(subPath)
    end
   }
  end
 end
end

class File
 def self.match?(path, patterns)
  if patterns.class == Regexp
   patterns = [patterns]
  end
  matched = false
  patterns.each{|p|
   if basename(path) =~ p
    matched = true
    break
   end
  }
  return matched
 end
 def self.forEachChild(path, skip = [])
  results = []
  Find.findWithin(path){|subPath|
   results << yield(subPath) unless match?(subPath, skip)
   Find.prune
  }
  return results
 end
 def self.list(path, skip = [])
  subPaths = []
  File.forEachChild(path, skip){|subPath|
   subPaths << subPath
  }
  return subPaths
 end
 def self.recurse(path, skip = [], &block)
  list(path, skip).each{|member|
   block.call(member)
  }
  # List the directory again in case the above block yield has modified the file list.
  list(path, skip).each{|member|
   recurse(member, skip, &block)
  }
 end
end

class Time
 def self.fromStamp(timeStamp)
   date, time = timeStamp.split(" ")
   dateParts = date.split("-")
   timeParts = time.split(":")
   mktime(dateParts[0], dateParts[1], dateParts[2], timeParts[0], timeParts[1], timeParts[2])
 end
 def toStamp
  strftime("%Y-%m-%d %I:%M:%S")
 end
end
		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..