Skip to content

Instantly share code, notes, and snippets.

View michaelfeathers's full-sized avatar

Michael Feathers michaelfeathers

View GitHub Profile
FIELDS_TEXT = "class A; def a; @a = @b; end; end"
FIELDS_SEXP = Ripper.sexp(FIELDS_TEXT)
[:program, [[:class, [:const_ref, [:@const, "A", [1, 6]]], nil,
[:bodystmt, [[:def, [:@ident, "a", [1, 13]], [:params, nil, nil, nil, nil, nil],
[:bodystmt, [[:assign, [:var_field, [:@ivar, "@a", [1, 16]]],
[:var_ref, [:@ivar, "@b", [1, 21]]]]], nil, nil, nil]]], nil, nil, nil]]]]
class Object
def ary?; is_a? Array; end
def str?; is_a? String; end
def nonempty_ary?
ary? && (not empty?)
end
end
def sexp_select sexp, symbols
ENCODER = Hash[('a'..'z').map {|x| [x,x] }].merge(Hash["aeiouya".chars.each_cons(2).to_a])
DECODER = ENCODER.invert
def encode string
string.chars.map {|c| ENCODER[c] || c }.join
end
def decode string
@michaelfeathers
michaelfeathers / gist:4704833
Last active December 12, 2015 03:09
Generating dot files from Ruby code.
require 'ap'
require 'ripper'
CLASS_TEXT = "class A; end; class B; end"
CLASS_SEXP = Ripper.sexp(CLASS_TEXT)
BIG_TEXT = "class A; def a; @a = b; end; def b; @d = a; @e = a; end; end; module B; def b; end; end"
BIG_SEXP = Ripper.sexp(BIG_TEXT)
def field_names
@field_names ||= @expression.flatten
.each_cons(2)
.select {|marker, _| marker == :@ivar }
.map {|_,name| field_name(name) }
end
Vector vList = new Vector(10);
BufferedReader listFile = new BufferedReader(new FileReader(emailListFile));
String line = null;
while ((line = listFile.readLine()) != null) {
vList.addElement(new InternetAddress(line));
}
listFile.close();
if (ls.debugOn)
log.put(new Date() + "> " + "Found " + vList.size() + " email ids in list");
ls.toList = new InternetAddress[vList.size()];
# :: [[a,b]] -> (a..a) -> b -> [[a,b]]]
def spread mappings, range, default_value = 0
occupied = Hash[mappings]
range.map { |index| [index, occupied[index] || default_value] }
end
# :: String -> [event] -> [[date, Int]]
def class_commit_monthly_timeline class_name, events
class_month_dates = events.select {|e| e.class_name == class_name }.map(&:date).map(&:month_start)
spread(class_month_dates.freq, month_range(class_month_dates.min, class_month_dates.max))
# :: [[a,b]] -> (a..a) -> b -> [[a,b]]]
def spread mappings, range, default_value = 0
occupied = Hash[mappings]
range.map { |index| [index, occupied[index] || default_value] }
end
@michaelfeathers
michaelfeathers / gist:4185398
Created December 1, 2012 21:55
Sometimes you just need to zip two hashes
def zip_hash hash_a, hash_b, missing_element = nil
all_keys = (hash_a.keys + hash_b.keys).uniq
result = {}
all_keys.each do |key|
result[key] = [hash_a[key] || missing_element, hash_b[key] || missing_element]
end
result
end
require 'ostruct'
require 'date'
class OrdersReport < Struct.new(:orders,:date_range)
def total_sales_within_date_range
orders.select {|order| date_range.include?(order.placed_at) }
.map(&:amount)
.reduce(0.0,:+)
end
end