Mixins

In addition to Models, you can achieve a lot of useful code reuse through the ModelMixin class. This allows you to define base functionality and reuse it as a mixin to one or more models later on.

The usage of these object types is very simple:

import datetime
import orb

class AuthorshipMixin(orb.ModelMixin):
  """
  Defines a re-usable class for tracking what user
  created a record, and the time when it was created.
  """
  created_by = orb.ReferenceColumn(reference='User')
  created_at = orb.DatetimeColumn()

  def onInit(self, event):
    self.set('created_by', User.currentRecord())
    self.set('created_at', datetime.datetime.now())
import orb
from .mixins import AuthorshipMixin

class User(orb.Table):
  id = orb.IdColumn()
  username = orb.StringColumn()

  @classmethod
  def currentRecord(cls):
    return getattr(cls, '__record', None)

  @classmethod
  def setCurrentRecord(cls, record):
    setattr(cls, '__record', record)

class Comment(AuthorshipMixin, orb.Table):
  """
  In addition to the schema columns, the authorship
  mixin will also add a created_by and created_at column
  to the Comment table
  """
  id = orb.IdColumn()
  text = orb.TextColumn()

class Ticket(AuthorshipMixin, orb.Table):
  id = orb.IdColumn()
  title = orb.StringColumn()
  description = orb.TextColumn()

In this example, the AuthorshipMixin will add the created_at and created_by columns to any model that wants to track it. Adding it to the Comment and Ticket models will let you reuse the creation logic without having to re-code it, or define it as a base table.