0.0
No commit activity in last 3 years
No release in over 3 years
Normalize deeply nested hash based on a schema
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 3.0
 Project Readme

normalizr

Like normalizr.js for Ruby hashes.

If you have JSON/YAML, then just parse the JSON/YAML into a hash and pass it in.

Installation

gem install normalizr.rb

Usage

Normalizr.normalize!(hash, schema)

Example

If we define the following schema...

comment = Schema.new('comments')
author = Schema.new('authors')
post  = Schema.new('posts', {
  author: author,
  comments: ArrayOf.new(comment)
})

...and have the following nested hash...

obj = {
  posts: [
    {
      id: 11,
      title: 'Relational normalization',
      author: {
        id: 22,
        name: 'Darkwing Duck'
      },
      comments: {
        id: 33,
        body: 'Interesting...'
      }
    }
  ]
}

...and then pass the hash and the schema to normalizr...

Normalizr.normalize!(obj, {
  posts: ArrayOf.new(post)
})

...then we get the following flat result, where collections are id-indexed hashes rather than plain arrays.

{
  posts: {
    :11 => {
      id: 11,
      title: 'Relational normalization',
      author: 22,
      comments: [33]
    }
  },
  authors: {
    :22 => {
      id: 22,
      name: 'Darkwing Duck'
    }
  },
  comments: {
    :33 => {
      body: 'Interesting...'
    }
  }
}

Remember: If you want to say Schema (and so forth) rather than Normalizr::Schema you have to include Normalizr.

Do you want new IDs?

If your hash does not have IDs, normalizr will generate them for you. If your hash do have IDs then normalizr will not overwrite them but assume you are using them appropriately. If your hash has IDs but you want to generate new IDs anyway, then invoke normalizr like this:

Normalizr.normalize!(obj, schema, { new_keys: true })

API Reference

TODO