class Mustermann::Caster

Class for defining and running simple Hash transformations.

@example

caster = Mustermann::Caster.new
caster.register(:foo) { |value| { bar: value.upcase } }
caster.cast(foo: "hello", baz: "world") # => { bar: "HELLO", baz: "world" }

@see Mustermann::Expander#cast

@!visibility private

Public Class Methods

new(*types, &block) click to toggle source

@param (see register) @!visibility private

Calls superclass method
# File lib/mustermann/caster.rb, line 17
def initialize(*types, &block)
  super([])
  register(*types, &block)
end

Public Instance Methods

cast(hash) click to toggle source

Transforms a Hash. @param [Hash] hash pre-transform Hash @return [Hash] post-transform Hash @!visibility private

# File lib/mustermann/caster.rb, line 44
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
caster_for(type, &block) click to toggle source

@param [Symbol, Regexp, cast, ===] type identifier for cast type (some need block) @return [#cast] specific cast operation @!visibility private

# File lib/mustermann/caster.rb, line 33
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
register(*types, &block) click to toggle source

@param [Array<Symbol, Regexp, cast, ===>] types identifier for cast type (some need block) @!visibility private

# File lib/mustermann/caster.rb, line 24
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