Skip to content

Instantly share code, notes, and snippets.

View liaden's full-sized avatar

Joel Johnson liaden

  • OmadaHealth
  • Atlanta
View GitHub Profile
letters = "ABCDEFGHIJKLMNOPRSTUVWXYZ"
map = {}
letters.each_char.each_with_index do |c, i|
map[c] = letters[(i+13)%26]
end
map.keys.each do |k|
map[k.downcase] = map[k].downcase
end
class Object
# as inspired by bash
def tee(*functions)
self.tap do
args.map { |arg| arg.call(self) }
end
end
end
class SomeClass
@liaden
liaden / gist:8543292ac7a02a2fb7fc
Last active August 29, 2015 14:11
because singletons are bad
# before
class X
# imperative, affects system state, depends on globals
def self.x
puts Config.data
end
end
X.x
@liaden
liaden / gist:2a09c245b26e7a67b0d3
Created March 19, 2015 19:40
Look at all tables and find matching columns.
def find_column_in_tables(filter)
tables = ActiveRecord::Base.connection.tables.map { |tname| tname.singularize.camelize.constantize rescue nil }.compact
column_names_by_table = tables.reduce({}) { |hash, table| hash.merge( table.name => table.column_names ) }
column_names_by_table.select { |key,value| value.any? { |column_name| column_name =~ filter } }
end
@liaden
liaden / ar.rb
Created August 3, 2015 22:35
active record without rails using sqlite in memory
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
ActiveRecord::Schema.define do
@liaden
liaden / maybe.rb
Last active September 25, 2015 22:16
Maybe, just maybe it will have a value
class Maybe
def initialize(item, &block)
@item = item
@block = block || proc { |item| !item.nil? }
end
def just
yield(@item) if @block.call(@item)
end
end
Maybe.new(5).just { |x| puts x }
@liaden
liaden / method_vs_local.rb
Created September 25, 2015 22:10
The existence of an unevaluated local changes things
class X
attr_accessor :x
def f
self.x = 2
if false
# try commenting out x=0 to see what happens.
x = 0
end
h1 = Hash.new { |h,k| h[k] = Hash.new(&h.default_proc) }.with_indifferent_access
h2 = h1.dup
h1['x']['y']['a'] = 5
h1['x']['y']['arr'] = [1,2,3]
h2['x']['y']['arr'] = [2,3,4]
h1['h'] = [1,2]
h2['f'] = [3,4]
h1.deep_merge!(h2) { |key, old_value, new_value| (Array(old_value) + Array(new_value)).uniq }
def level(hash, index)
if level == 1
return if block_given?
yield hash.values
else
hash.values
end
end
# or hash.values.reduce(Set.new) ....
hash.values.map { |subhash| level(subhash, index-1) }.flatten.uniq
@liaden
liaden / gc.c
Created July 3, 2018 16:01
ree gc.c
/**********************************************************************
gc.c -
$Author$
$Date$
created at: Tue Oct 5 09:44:46 JST 1993
Copyright (C) 1993-2003 Yukihiro Matsumoto
Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
Copyright (C) 2000 Information-technology Promotion Agency, Japan
**********************************************************************/