ModeloEspecial: An ORM based on Backbone.JS

439
Vote up!

ModeloEspecial is an ORM that is inspired heavily by Backbone.Model. It takes an object oriented approach to database interaction.

We are using this in production, and it has already saved us hundreds of lines of code, in addition to making it more modular and understandable.

This file previews how we use it internally, to map records in the database and get a sprite ready to use.

local modeloEspecial = ModeloEspecial:new {
	name = "yogodb",
	debug = settings.debugSql
}

local function migrate(schemaVersion, exec)
	if schemaVersion < 1 then
		log "migrating schema to v1"

		local createPlayers = [[CREATE TABLE IF NOT EXISTS players (
gender VARCHAR,
country VARCHAR,
sombrero INTEGER,
level INTEGER,
currentExp INTEGER,
firstRun INTEGER,
name VARCHAR,
color1 INTEGER,
color2 INTEGER,
totalTimePlayed INTEGER,
remoteplayerid VARCHAR,
wordId VARCHAR);]]
		exec(createPlayers)
	end
	return 1
end

modeloEspecial:migrate(migrate)
local Model = require'modeloespecial'.Model
local Player = Model:extend {table = 'players'}

Player.sequenceData = {
	{name = "idle", start = 1, count = 8, time = 800},
	{name = "jump", start = 9, count = 8, time = 800},
	-- other sequence data
}
Player.sheetData = {
  width = 128,
  height = 128,
  numFrames = 16,
}

function Player:getSprite(parent)
	assert(self:isInstanceOf(Player), 'Called .getSprite() instead of :getSprite()')

	local group = display.newGroup()

  -- the spritesheet is in either images/player/male.png or images/player/female.png

  local path = string.format("images/player/%s.png", self:get'gender')
	local sheet = graphics.newImageSheet(path, self.class.sheetData)
	local sprite = display.newSprite(group, sheet, self.class.sequenceData)
	group.sprite = sprite
	function group:playSequence(name)
	  self.sprite:setSequence(name)
	  self.sprite:play()
	end

	if parent then
		parent:insert(group)
	end
	return group
end

return Player
local storyboard = require 'storyboard'
local Player = require 'player'
local scene = storyboard.newScene()

local player

function scene:createScene()

end

function scene:enterScene()
  player = Player:fetchById(1)
  player:getSprite(scene.view)
end

function scene:exitScene()
  player = nil
end

scene:addEventListener('createScene', scene)
scene:addEventListener('enterScene', scene)
scene:addEventListener('exitScene', scene)

return scene

Category: 
Contributor: 
jeduan