The Crystal Programming Language Forum

Cast from string to type

i dont know if there any way to cast from string to class type
class A
a =
new_var = a.to_s
how to turn new_var to be type A ?

You’d have to use some sort of serialization format. E.g. JSON or YAML. JSON::Serializable - Crystal 1.2.2 can help with that.

thank you,
how this can help with a complex type like HTTP

Can you share more about what you’re wanting to do?

for example i want to save an instance of HTTP::WebSocket in the database as string mostly an retrieve it again to work width it

because of your help i get hint how it would work ,but if you have a concrete example it would be great

:thinking: I’m not sure that would be a good idea. Probably would be better to just save the things that makeup the object and create another one after reading it from the DB I’d say.

1 Like

Agreed with @Blacksmoke16. A WebSocket runs on top of a TCP socket, which is tied to a POSIX file descriptor. On most operating systems, file descriptors are process-specific (though in some they can be shared to child processes spawned via fork), so the database process and the application process would have no overlap in their sets of file descriptors, making it literally impossible to persist.

If you’re building a WebSocket server, you’ll need to keep a set of them in memory inside your application. Maybe that’s in a Set, or if you’re building some sort of pub/sub-style setup like Pusher, you could keep a Hash(String, Set(HTTP::WebSocket)) that tracks which WebSockets are subscribed to which channels. But it all has to remain in-memory inside the application.

If the application is restarted, that list of WebSockets goes away because it only exists in memory, but that’s the correct behavior because the operating system’s TCP stack would close all of its WebSockets anyway, requiring all of its clients to reconnect.

1 Like

thank you very much man for your help and time :)

thanks man for your very informative replay,
your strategy also works great for me which you describe as “pub/sub-style setup like Pusher”
thank you very much