ruby - How to compare the structure and type of two hash tables, not the values -
i trying compare structure of 2 hash tables. want see if given hash table subset of master table.
example of valid sub-table:
master_table = {a: string, b: object, c: { nested_a: integer, nested_b: integer} } my_table = {a: 'cool value', c: {nested_b: 540}
example of invalid sub-table
my_table = {a: wrongtype.new}
or
my_table = {a: 'cool value', new_key: "i don't belong here!"}
edit: if looks duck , quacks kinda duck, accept duck.
i have data driven application user have provide config file defines application's behavior. want make sure users' configuration files match structure , types defined in master config file.
in regards sergio tulentsev's comment, issue above in first example of invalid sub-table, :a's type not valid according master table. in second case, there exists key not present in master table , therefor incorrect.
code
def valid?(master_table, my_table) my_table.all? |k,v| case master_table.key?(k) when true mv = master_table[k] case v when hash mv.is_a?(hash) && valid?(mv, v) else mv.is_a?(class) && v.is_a?(mv) end else false end end end
examples
master_table = {a: string, b: object, c: {nested_a: integer, nested_b: integer}} my_table = {a: 'cool value', c: {nested_b: 540}} valid?(master_table, my_table) #=> true my_table = {a: 'cool value', new_key: "i don't belong here!"} valid?(master_table, my_table) #=> false my_table = {a: 'cool value', new_key: "i don't belong here!"} valid?(master_table, my_table) #=> false my_table = {a: 'cool value', c: 42} valid?(master_table, my_table) #=> false
master_table = {a: string, b: object, c: {nested_a: {nested_b: {nested_c: integer}}}} my_table = {a: 'cool value', b: [1,2,3], c: {nested_a: {nested_b: {nested_c: 42}}}} valid?(master_table, my_table) #=> true my_table = {a: 'cool value', b: [1,2,3], c: {nested_a: {nested_b: {nested_c: 'cat'}}}} valid?(master_table, my_table) #=> false my_table = {a: 'cool value', b: [1,2,3], c: {nested_a: {nested_b: 42}}} valid?(master_table, my_table) #=> false
Comments
Post a Comment