data = { name: "Joe", password: "secret" }
copy = BetterHash.new(data)
copy.filter!([:password])
copy.inner_object # => {:name=>"Joe", :password=>"[FILTERED]"}
Last active
December 7, 2015 23:33
-
-
Save natesalisbury/635ec91ce9230aa14121 to your computer and use it in GitHub Desktop.
Footing Brainstorm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment