class Stunted::FunctionalHash
Public Class Methods
make_maker(*shapes)
click to toggle source
# File lib/stunted/functional-hash.rb, line 80 def self.make_maker(*shapes) klass = shaped_class(*shapes) ->(inits={}) { klass.new(inits) } end
new(hash = {})
click to toggle source
# File lib/stunted/functional-hash.rb, line 7 def initialize(hash = {}) hash.each do | k, v | self[k] = v if k.is_a?(Symbol) if self.respond_to?(k) $stderr.puts("Warning: #{k.inspect} overrides existing Hash method.") end instance_eval("def #{k}; self[#{k.inspect}]; end") end end end
Public Instance Methods
-(keys)
click to toggle source
# File lib/stunted/functional-hash.rb, line 67 def -(keys) keys = [keys] unless keys.respond_to?(:first) remove(*keys) end
[](key)
click to toggle source
# File lib/stunted/functional-hash.rb, line 72 def [](key) fetch(key, nil) end
change_within(*args)
click to toggle source
# File lib/stunted/functional-hash.rb, line 41 def change_within(*args) if (args.first.is_a? Hash) merge(args.first) else key = args.first rest = args[1..-1] merge(key => fetch(key).change_within(*rest)) end end
component(hash)
click to toggle source
# File lib/stunted/functional-hash.rb, line 85 def component(hash) # For now, just one pair field = hash.keys.first shape = hash.values.first secondary_module = Module.new shape.instance_methods.each do | meth | defn = "def #{meth}(*args) merge(#{field.inspect} => self.#{field}.#{meth}(*args)) end" secondary_module.module_eval(defn) end merge(field => self[field].become(shape)).become(secondary_module) end
fetch(key, *args, &block)
click to toggle source
Calls superclass method
# File lib/stunted/functional-hash.rb, line 19 def fetch(key, *args, &block) current = super(key, *args, &block) if current.is_a?(Proc) if current.arity == 0 self[key] = current.() else self[key] = current.(self) end else current end end
merge(hash)
click to toggle source
Calls superclass method
# File lib/stunted/functional-hash.rb, line 32 def merge(hash) self.class.new(super(hash)) end
Also aliased as: +
only(*keys)
click to toggle source
# File lib/stunted/functional-hash.rb, line 76 def only(*keys) self.class[*keys.zip(self.values_at(*keys)).flatten(1)] end
remove(*keys)
click to toggle source
# File lib/stunted/functional-hash.rb, line 51 def remove(*keys) new_hash = dup keys.each { | key | new_hash.send(:delete, key) } self.class.new(new_hash) end
remove_within(*args)
click to toggle source
# File lib/stunted/functional-hash.rb, line 57 def remove_within(*args) key = args.first rest = args[1..-1] if (args.count <= 1) remove(key) else merge(key => fetch(key).remove_within(*rest)) end end
transform(symbol) { |self| ... }
click to toggle source
# File lib/stunted/functional-hash.rb, line 37 def transform(symbol) merge(symbol => yield(self[symbol])) end
with_replacement_methods(hash, &block)
click to toggle source
# File lib/stunted/mocking.rb, line 17 def with_replacement_methods(hash, &block) self.class.with_replacement_methods(hash, &block) end