Last active
January 30, 2020 17:34
-
-
Save digitalextremist/d8102988c4cba4f69fec68d6f3dd8e63 to your computer and use it in GitHub Desktop.
Clarity.dismantler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Clarity | |
alias Value = Nil | String | Bool | | |
Int64 | | |
Int32 | | |
Float64 | | |
Array(Value) | | |
Hash(String, Value) | |
def self.dismantler(a) | |
dismantle_hash(a) | |
end | |
def self.dismantle_hash(h) | |
clean = Hash(String, Clarity::Value).new | |
h.each { |k,v| | |
Gnosis.debug "#{k.class} => #{v.class}" | |
clean[k.as(String)] = if v.is_a?(Hash) | |
dismantle_hash(v) | |
elsif v.is_a?(Array) | |
dismantle_array(v) | |
else | |
dismantle_else(v) | |
end | |
} | |
clean | |
end | |
def self.dismantle_array(a) | |
clean = Array(Clarity::Value).new | |
a.map { |i| | |
if i.is_a?(Hash) | |
clean.push dismantle_hash(i) | |
elsif i.is_a?(Array) | |
clean.push dismantle_array(i) | |
else | |
clean.push dismantle_else(i) | |
end | |
} | |
clean | |
end | |
def self.dismantle_else(d) | |
if d.is_a?(String) | |
d.as(String) | |
elsif d.is_a?(Bool) | |
d.as(Bool) | |
elsif d.is_a?(Int32) | |
d.as(Int32) | |
elsif d.is_a?(Int64) | |
d.as(Int64) | |
elsif d.nil? | |
nil | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "gnosis" | |
require "msgpack" | |
require "mongo/bson" | |
require "../src/clarity/dismantler" | |
query = { | |
"age" => { | |
"$gt" => 30, | |
"$lt" => 100, | |
"$eq" => nil | |
}, | |
"array" => [ | |
"test", | |
1, | |
true, | |
nil | |
] | |
} | |
#de Native Hash to MessagePack encoded string... | |
Gnosis.debug msgpack = String.new(query.to_msgpack) | |
#de Encided string to Hash(String, MessagePack::Type) | |
query_reborn = Hash(String, MessagePack::Type).from_msgpack(msgpack) | |
#de The goal: | |
Gnosis.debug bson = Clarity.dismantler(query_reborn) #de .to_bson | |
Gnosis.debug bson.to_bson, "Dismantled BSON" | |
Gnosis.debug bson2 = { "test" => true }.to_bson | |
Gnosis.debug bson2 = { "test1" => true, "test2" => [ true, nil, "false" ] }.to_bson |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment