Sha256: 9bd4dd4a6d81f4fbb5f7f19631c5a89c8f876f98ab2fe91b682eff19a4bb877e

Contents?: true

Size: 912 Bytes

Versions: 1

Compression:

Stored size: 912 Bytes

Contents

require_relative 'addr'

module Kamerling
  module Mapper
    module_function

    def from_h(klass, hash, repos: Repos)
      attributes = hash.map do |key, value|
        case key
        when :host, :port, :prot then [:addr, Addr.new(hash)]
        when /_uuid$/            then object_pair_from(key, value, repos)
        else                          [key, value]
        end
      end.to_h
      klass.new(attributes)
    end

    def object_pair_from(key, value, repos)
      type = key[/(.*)_uuid$/, 1].to_sym
      [type, repos[Kamerling.const_get(type.capitalize)][value]]
    end

    def to_h(object)
      object.to_h.reduce({}) do |hash, (key, value)|
        hash.merge case value
                   when Addr then value.to_h
                   when Hash then { :"#{key}_uuid" => value[:uuid] }
                   else           { key => value }
                   end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kamerling-0.0.3 lib/kamerling/mapper.rb