Ruby Socket Inheritance

Posted by Jarsen on Stack Overflow See other posts from Stack Overflow or by Jarsen
Published on 2010-05-29T22:56:53Z Indexed on 2010/05/29 23:02 UTC
Read the original article Hit count: 329

Filed under:
|
|

I'm writing a Ruby class that extends TCPSocket. Assume it looks something like this:

class FooSocket < TCPSocket
    def hello
        puts 'hello'
    end
end

I have a TCPServer listening for incoming connections

server = TCPServer.new 1234
socket = server.accept

When my server finally accepts a connection, it will return a TCPSocket. However, I want a FooSocket so that I can call socket.hello.

How can I change TCPSocket into a FooSocket?

I could duck-punch the methods and attributes I want directly onto the TCPSocket class, but I'm using it elsewhere and so I don't want to do that.

Probably the easiest solution is to write a class that encapsulates a TCPSocket, and just pass the socket returned by accept as a param. However, I'm interested to know how to do it through inheritance—I've been trying to bend my mind around it but can't figure it out.

Thanks in advance.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about inheritance