Sha256: 6cd67161954d447e2e86a6e932579a2ca75d7d81a42877230b82ce86aa4d8a82

Contents?: true

Size: 1.06 KB

Versions: 2

Compression:

Stored size: 1.06 KB

Contents

module PipeRpc
  class DeepMapper
    def self.map(object, &mapper)
      case object
      when Hash then object.map{ |k, v| [k, map(v, &mapper)] }.to_h
      when Array then object.map{ |item| map(item, &mapper) }
      else yield object
      end
    end

    def self.to_transport(object, hub)
      map(object) do |value|
        if value.respond_to? :__rpc_server_id__
          "__rpc_client__#{value.__rpc_server_id__}"
        elsif value.respond_to? :to_rpc_server_id
          hub.servers.add(value) unless hub.servers.registered? value.to_rpc_server_id
          "__rpc_server__#{value.to_rpc_server_id}"
        else
          value
        end
      end
    end

    def self.from_transport(object, hub)
      map(object) do |value|
        if value.is_a?(String) and value.start_with?('__rpc_client__')
          hub.servers[value.sub('__rpc_client__', '').to_sym]
        elsif value.is_a?(String) and value.start_with?('__rpc_server__')
          Client.new(value.sub('__rpc_server__', '').to_sym, hub)
        else
          value
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pipe_rpc-2.2.2 lib/pipe_rpc/deep_mapper.rb
pipe_rpc-2.2.1 lib/pipe_rpc/deep_mapper.rb