Skip to content

Instantly share code, notes, and snippets.

@EnriqueVidal
Created October 24, 2010 18:05
Show Gist options
  • Save EnriqueVidal/643755 to your computer and use it in GitHub Desktop.
Save EnriqueVidal/643755 to your computer and use it in GitHub Desktop.
Person = {
instance: function(name, lastname)
{
var base = this;
base._private = {}
base._public = {}
base._private.name = name;
base._private.lastname = lastname;
base._public.getName = function() { return base._private.name; }
base._public.getLastName = function() { return base._private.lastname; }
return base._public;
},
version: '0.0.1'
}
nite_owl = new Person.instance('daniel', 'dreiberg');
ozymandias = new Person.instance('adrian', 'veidt');
console.log(nite_owl.getName());
console.log(ozymandias.getName());
console.log(Person.version);
console.log(nite_owl);
Object.prototype.all = new Array();
Object.prototype.find = function(id) {
for (var i=0; i < this.all.length; i++)
{
if (this.all[i].id == id)
return this.all[i];
}
return null;
}
// Poor man's ActiveRecord::Base model class in js
Person = {
type: 'Person',
build: function(parameters)
{
var base = this;
base._private = parameters;
base._public = {};
base._private.id = null;
base._public.new_record = true;
base._public.type = Person.type;
base._public.name = function() { return base._private.name; }
base._public.last_name = function() { return base._private.last_name; }
base._public.set_name = function(value) { base._private.name = value; }
base._public.set_last_name = function(value) { base._private.last_name = value; }
base._public.save = function() {
if (base._public.new_record) {
base._private.id = Person.all.length + 1;
Person.all.push(base._private);
base._public.new_record = false;
}
return true;
}
return base._public;
}
}
nite_owl = new Person.build({ name: 'daniel', last_name: 'dreiberg' });
ozymandias = new Person.build({ name: 'adrian', last_name: 'veidt' });
nite_owl.save();
ozymandias.save();
console.log(Person.all);
console.log(Person.find(1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment