Skip to content

Instantly share code, notes, and snippets.

@sethladd
Created June 8, 2013 19:20
Show Gist options
  • Select an option

  • Save sethladd/5736289 to your computer and use it in GitHub Desktop.

Select an option

Save sethladd/5736289 to your computer and use it in GitHub Desktop.
One attempt at a Persistable mixin in Dart.
import 'dart:mirrors';
import 'dart:async';
// TODO: inject the persistance storage driver
abstract class Persistable {
int _dbId;
static const constructor = const Symbol('fromPersistance');
static Future load(int id, Type type) {
// Magically pretend to get this from a Database.
var data = {'id': 1, 'firstName': 'Bob', 'lastName': 'Smith'};
var classMirror = reflectClass(type);
// See dartbug.com/11161
if (classMirror.constructors[new Symbol('$type.fromPersistance')] == null) {
throw '$type should have a constructor $constructor';
}
var instance = classMirror.newInstance(constructor, [data]);
var object = instance.reflectee;
// Mixins can't have constructors, so I set the ID here.
// Not sure if there's a better way.
object._dbId = data['id'];
// A real DB would use a Future-based API.
return new Future.value(object);
}
Future store() {
var map = toMap();
// Magically do the query here with the map of fields.
// Use dbId to identify the object.
return new Future.value(true);
}
Future<int> create() {
if (dbId != null) {
throw 'Already has as ID of $dbId';
}
// Tnsert into database, get ID.
_dbId = 100;
return new Future.value(dbId);
}
Map toMap();
// This assumes there's no reason for code to change an ID.
int get dbId => _dbId;
}
class Person extends Object with Persistable {
String firstName;
String lastName;
Person(this.firstName, this.lastName);
Person.fromPersistance(Map data) {
firstName = data['firstName'];
lastName = data['lastName'];
}
Map toMap() => {'firstName': firstName, 'lastName': lastName};
String toString() => '$dbId $firstName $lastName';
}
void main() {
var p = new Person('Bob', 'Smith');
p.create()
.then((id) => print(id))
.then((_) => Persistable.load(p.dbId, Person))
.then((newP) => p = newP)
.then((_) {
p.firstName = 'Alice';
return p.store();
})
.then((_) => print('completed store'))
.catchError(print);
// Persistable.load(1, Person)
// .then((Person p) {
// print(p);
// p.firstName = 'Alice';
// return p.store();
// })
// .then((_) => print('completed store'))
// .catchError(print);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment