Skip to content

Instantly share code, notes, and snippets.

@natesalisbury
Last active December 7, 2015 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natesalisbury/635ec91ce9230aa14121 to your computer and use it in GitHub Desktop.
Save natesalisbury/635ec91ce9230aa14121 to your computer and use it in GitHub Desktop.
Footing Brainstorm
class BetterHash < Footing
def filter!(keys, replacement: "[FILTERED]")
should_replace = lambda do |key|
replace = false
keys.each do |k|
break if replace
replace = k.is_a?(Regexp) ? key.to_s =~ k : key.to_s == k.to_s
end
replace
end
each do |key, value|
if value.is_a?(::Hash)
value.filter!(keys, replacement: replacement)
elsif value.is_a?(Enumerable)
value.each do |val|
if val.is_a?(::Hash)
value.filter!(keys, replacement: replacement)
end
end
else
value = replacement if should_replace.call(key)
self[key] = value
end
end
self
end
end
require 'delegate'
class Footing < SimpleDelegator
class << self
def copy(o)
Marshal.load Marshal.dump(o)
end
end
def initialize(o, copy: true)
o = self.class.copy(o) if copy
super(o)
end
def inner_object
__getobj__
end
end
data = { name: "Joe", password: "secret" }
copy = BetterHash.new(data)
copy.filter!([:password])
copy.inner_object # => {:name=>"Joe", :password=>"[FILTERED]"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment