let’s say I have a struct with the ability to take a Hash and assign it’s properties accordingly.
I will provide an example with rethinkDB but really it can happen with every database library out there.
When querying the database the result of the query is of a type called RethinkDB::QueryResult
which is really just an alias for many primitives available in Crystal.
On the other hand I got a struct which looks like:
abstract struct Cybergarden::Items::Server
include JSON::Serializable
property capacity
property processors
property price # money per second
property maintability
def analyze_mps()
mps = 0
processor.each {|cpu| mps+=cpu.mps}
mps
end
def as_h()
{
capacity: @capacity,
processors: @processors.map &.as_h,
price: @price,
maintability: @maintability
}
end
def from_h(payload : Hash(String, String | Array(Hash(String, String | Int32) | Int32)))
@capacity = payload["capacity"]
@processors = payload["processors"].map Cybergarden::Items::CpuTypes[&["type"]].new().from_h()
@price = payload["price"]
@maintability = payload["maintabiltiy"]
end
end
so when querying the database to find the servers a user own I would like to make a new struct instance out of the available data, the only issue is, the data is RethinkDB::QueryResult
and when calling .as_h
on it it’s still Hash(String, RethinkDB::QueryResult)
and I still won’t be able to do something like
server = CyberServerTierOne.new.from_h(theHashFromTheQuery)
since it doesn’t expect a QueryResult but more specific Hash(String, String | Array(Hash(String, String | Int32) | Int32))
Someone has an idea on how I can implement such stuff? without doing the obvious of making all the property types to be Rethink::QueryResult
Thank you.