Skip to content

Instantly share code, notes, and snippets.

@lifehackett
Created April 22, 2015 20:49
Show Gist options
  • Save lifehackett/27f55fb1d8779c618664 to your computer and use it in GitHub Desktop.
Save lifehackett/27f55fb1d8779c618664 to your computer and use it in GitHub Desktop.
Serialization for converting between JS and Rails naming conventions
'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;
@justin808
Copy link

Looks pretty awesome. Let's see an ES6 version with a few JS tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment