Skip to content

Instantly share code, notes, and snippets.

@svenyurgensson
Last active December 17, 2015 23:39
Show Gist options
  • Save svenyurgensson/5690930 to your computer and use it in GitHub Desktop.
Save svenyurgensson/5690930 to your computer and use it in GitHub Desktop.
class Hash
def apply_schema(schema)
new_hash = {}
schema.each do |el|
if Hash === el
el.each do |k,v|
raise ArgumentError.new("Bad schema on key: #{k}, value: #{v}. Value have to be an array") unless Array === v
new_hash[k] = []
next unless self.has_key?(k)
v.each do |vv|
if Array === vv
new_hash[k] = self[k].map{|sel| sel.apply_schema(vv)}
else
new_hash[k] = self[k].apply_schema(v)
end
end
end
elsif self.has_key?(el)
new_hash[el] = self[el]
else
new_hash[el] = nil
end
end
new_hash
end
end
# Test schema
schema = [
:aaa,
:bbb,
:ooo,
{:ccc => [:ddd, :ggg]},
{:zzz => [[:hhh, :kkk, :mmm]]},
]
input = {
:aaa => "22",
:aaaa => "New 22",
:bbb => "434",
:ccc => {:ddd => "abc",
:ddddd => "Not needed",
:ggg => "Needed",
:hard_to_believe => []},
:zzz => [
{:hhh => 126,
:hhhh => "Don't need",
:kkk => "Existing key"},
{:hhh => "DoobyDo",
:kkk => "Needed",
:mmm => "Existing key"}
]
}
output = {
:aaa => "22",
:bbb => "434",
:ooo => nil,
:ccc => {:ddd => "abc", :ggg => "Needed"},
:zzz => [{:hhh => 126, :kkk => "Existing key", :mmm => nil},
{:hhh=>"DoobyDo", :kkk=>"Needed", :mmm=>"Existing key"}]
}
puts
puts "schema:\n #{schema}"
puts "input:\n #{input}"
puts "desired_output:\n #{output}"
puts "apply:\n #{input.apply_schema(schema)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment