Useful snippets of Ruby code.
Contents
Syntactic Sugar: “with”
################################################### # Tim Burk's Syntactic Sugar: "with" # def with(x) yield x if block_given? x end # ex: # button = with(complex Button.new expression) do |b| # b.setSize ... # b.setText ... # b.setColor ... # end
Auto-require All .rb Files in a Folder
###################################################
# Tim Burk's Auto-require all .rb files in a directory
#
# Tim wrote:
# > Here's a code excerpt that does the job. Just give it a
# > directory and it will add it to the ruby load path # > ($:.push)
# > and then require all the .rb files in the directory. It
# > also subtracts out the current file so that it can be in the
# > same directory as the others and not get required twice.
#
def require_all_files(path)
$:.push path # resource path
rbfiles = Dir.entries(path).select {|x| /\.rb\z/ =~ x}
rbfiles -= [ File.basename(__FILE__) ]
rbfiles.each do |path|
require( File.basename(path) )
end
end
Process Each Line in a File, Skipping Comments
################################################### # Standard line processing from PickAxe # while gets next if /^#/ # Skip comments parseLine unless /^$/ # Don't parse empty lines end def parseLine ... end
Grep Method on an Enumerable (like a File)
###################################################
# Grep method in enumerable
#
File.open("ordinal").grep /d$/ do |line|
print line
end
Implementing “each”
###################################################
# Implementing "each"
# From the Ruby Quick Ref at
# https://www.zenspider.com/Languages/Ruby/QuickRef.html
#
# By defining the method #each and including Enumerable, you
# get to use all the methods in Enumerable:
#
class Mailbox
include Enumerable
# ...
def each
@mail.each do
# ...
yield
end
end
end
I/O idioms
################################################### # I/O Idioms # ARGF.read() # --get a string containing concatenated contents # of all files specified on command line, or # obtained from standard input ARGF.readlines() # --get an array Note: # --a reference to ARGF "swallows" the command line # arguments, so they are no longer available
Fixing “Insecure writable dir” Error
################################################### # Warning: Insecure writable dir (workaround) # ------------------------------------------- # Some things cause ruby to interact with the # environment in ways that cause a message to be # generated: # # warning: Insecure world writable dir # # In my case, I have directories containing # development tools that, for reasons unknown, # have a world-writable parent directory. It's # not something I can change, so I have to find # ways to suppress the warning. # # `ls *.rb` # No warning for this # `ls` # Generates the warning # `eval ""; ls` # Workaround to kill the warning # # path = ENV["PATH"] # Warning for this, too
Search Contents of Files
###################################################
# Search contents of files
#
Dir['**/*.html'].each do |path|
File.open( path ) do |f|
f.grep( /search_string/ ) do |line|
puts path, ': ', line
end
end
end
Access Shell-style Utilities
################################################### # Access shell-style utilities # require 'fileutils' # for cd, pwd, mkdir_p, rm_rf, etc. # for help: ri FileUtils (h,q)
List Files in a Directory
###################################################
# LIST FILES IN A DIRECTORY
#
files = Dir.chdir('lib') { Dir['**/*.rb'] }
Find the site_lib folder
###################################################
# Find the site_lib dir for this version of Ruby
# Cannibalized from the Rake's install.rb which is
# much more robust.
# => /RUBY_DIR/lib/ruby/site_ruby/1.8
#
require 'rbconfig'
include Config
version = CONFIG["MAJOR"]+"."+CONFIG["MINOR"]
SITE_LIB =
File.join(CONFIG["libdir"], "ruby", "site_ruby", version)
#usage:
# INSTALL_DIR = "#{SITE_LIB}/dev"
Please share!

1 Comment