Skip to content

Latest commit

 

History

History
61 lines (46 loc) · 1.86 KB

2014-02-05.md

File metadata and controls

61 lines (46 loc) · 1.86 KB

Deepak

Fantasy fiction book recommendation. The Red Knight http://www.goodreads.com/book/show/13616278-the-red-knight
It talks about memory palace which was actualy used in ancient greece and in modern memory tournaments
It is a core part of their magic system

http://en.wikipedia.org/wiki/Method_of_loci
http://www.wikihow.com/Build-a-Memory-Palace

hemant

Using JSON Schema's

Lets suppose you are recieving a json message roughly of format:

{
  'id' : 'abc-123',
  'account' : {
      'id' : 'acc-123',
      'name' : 'Codemancers'
  },
  'resource' : {
      'id' : 'srv-123',
      'name' : 'Codemancers CI server'
  }
}

When processing this incoming json you know that 'id' field must be present, similary account field must have and id and there must be a resouce field and that field must have an id field too. Traditionally we solve this by using if/elses and rejecting the json if it is missing some fields. For example:

json_data = JSON.parse(imcoming_string)
return if json_data['id'].blank || json_data['account'].blank? || ...

A really nice approach of solving this problem is to use json schemas. With them I can define a schema for above json:

{
    'type' : 'object',
    'properties' : {
      'id' : { 'type' : 'string'},
      'account': {
          'type' : 'object',
          'properties' : {
              'id' : {'type' : 'string'},
              'name': {'type' : 'string'}
          },
          'required': ['id']
      }
    },
    required: ['id', 'account', 'resource']
}

And then rather than playing whack-a-mole with incoming json, using the gem https://github.com/hoxworth/json-schema we can do:

JSON::Validator.validate(schema, data)

and boom code is much simpler and more exhaustive.