Created
April 22, 2015 20:49
-
-
Save lifehackett/27f55fb1d8779c618664 to your computer and use it in GitHub Desktop.
Serialization for converting between JS and Rails naming conventions
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
'use strict'; | |
var Model = require('ampersand-model'); | |
var _ = require('lodash'); | |
var CAMEL_CASE = 'camelCase'; | |
var SNAKE_CASE = 'snakeCase'; | |
var BaseModel = Model.extend({ | |
initialize: function () { | |
this._originalFns = { | |
serialize: _.bind(Model.prototype.serialize, this) | |
}; | |
}, | |
toSnakeCase: function (obj) { | |
return this._toCase(obj, SNAKE_CASE); | |
}, | |
toCamelCase: function (obj) { | |
return this._toCase(obj, CAMEL_CASE); | |
}, | |
_toCase: function (obj, toCaseFnName) { | |
var res = {}; | |
var transformedKey; | |
_.each(obj, function (value, key) { | |
transformedKey = _[toCaseFnName](key); | |
if (_.isArray(value)) { | |
res[transformedKey] = _.toArray(this._toCase(value, toCaseFnName)); | |
} else if (_.isObject(value)) { | |
res[transformedKey] = this._toCase(value, toCaseFnName); | |
} else { | |
res[transformedKey] = value; | |
} | |
}, this); | |
return res; | |
} | |
}); | |
module.exports = BaseModel; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks pretty awesome. Let's see an ES6 version with a few JS tests.