carloabelli
carloabelli

Reputation: 4349

Ruby Method for Casting

I am new to ruby development and I am making a simple chat server encrypted over TLS.

I have managed to get the basic server running however I now want to add special properties to each of the connected clients (username, etc.)

I have this class which I plan to use for each client that connects:

class Client < OpenSSL::SSL::SSLSocket
    attr_accessor :username
    ...
end

I need to get a Client object from the OpenSSL::SSL::SSLServer.accept function in order to set the username attribute. I am used to C type languages where casting would do the trick but Google has told me that this is not the case in Ruby.

What is the Ruby way of doing this?

Upvotes: 0

Views: 55

Answers (2)

Lex Lindsey
Lex Lindsey

Reputation: 531

There are essentially 2 ways to solve your problem:

  1. delegation: create Client as a wrapper with an instance variable of class OpenSSL::SSL::SSLSocket. Client would then have to understand and forward messages to SSLSocket. Could get complicated.
  2. extension: use class_eval to add instance variables and/or methods directly to SSLSocket. This is a commonly-used Ruby approach.

Upvotes: 0

Ismael
Ismael

Reputation: 16730

You don't need casting in Ruby. It's a dynamic language. So what matters is if the object knows how to respond to a message (method).

Upvotes: 2

Related Questions