class Mustermann::Caster
@!visibility private
@see Mustermann::Expander#cast
caster.cast(foo: “hello”, baz: “world”) # => { bar: “HELLO”, baz: “world” }
caster.register(:foo) { |value| { bar: value.upcase } }
caster = Mustermann::Caster.new
@example
Class for defining and running simple Hash transformations.
def cast(hash)
-
(Hash)- post-transform Hash
Parameters:
-
hash(Hash) -- pre-transform Hash
def cast(hash) return hash if empty? merge = {} hash.delete_if do |key, value| next unless casted = lazy.map { |e| e.cast(key, value) }.detect { |e| e } casted = { key => casted } unless casted.respond_to? :to_hash merge.update(casted.to_hash) end hash.update(merge) end
def caster_for(type, &block)
-
(#cast)- specific cast operation
Parameters:
-
type(Symbol, Regexp, #cast, #===) -- identifier for cast type (some need block)
def caster_for(type, &block) case type when Symbol, Regexp then Key.new(type, &block) else type.respond_to?(:cast) ? type : Value.new(type, &block) end end
def initialize(*types, &block)
-
() --
def initialize(*types, &block) super([]) register(*types, &block) end
def register(*types, &block)
-
types(Array) -- identifier for cast type (some need block)
def register(*types, &block) return if types.empty? and block.nil? types << Any.new(&block) if types.empty? types.each { |type| self << caster_for(type, &block) } end