Last active
August 29, 2015 14:09
-
-
Save luk3thomas/93c7ff00a27095c9fdad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Model = require "lib/model" | |
class Card extends Model | |
defaults: | |
name: "" | |
value: "" | |
transform: (name, value)-> | |
return switch name | |
when "name" then value.trim() | |
when "value" then +value | |
else value | |
validator: -> | |
blank = (name)-> | |
(d) -> | |
not d[name]? or d[name] is "" | |
@.add_validation "name", "name cannot be blank", blank("name") | |
@.add_validation "value", "value cannot be blank", blank("value") | |
module.exports = Card |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Model | |
constructor: (args)-> | |
# enfore new'd models | |
unless @ instanceof Model | |
return new Model(args) | |
# first args must be an object, | |
# if it is undefined, then we pass | |
# an empty object | |
if args is undefined | |
args = {} | |
unless args.length is undefined and typeof args is "object" | |
throw new TypeError "args must be a javascript object" | |
# extend model attributes onto the | |
# model defaults, then add them to | |
# the model. | |
@.attributes = {} | |
@.attributes[k] = v for k,v of @.defaults | |
@.attributes[k] = v for k,v of args | |
# Validations | |
# | |
# Load any custom data validations | |
@.validations = [] | |
@.validator ?= -> | |
@.validator.call(@) | |
# Transforms | |
# | |
# Transform a piece of data before save | |
# Create a phony transform if the model | |
# does not specify | |
@.transform ?= (name, value) -> value | |
# Getters and setters | |
get: (name)-> | |
@.attributes[name] | |
set: (name, value)-> | |
@.attributes[name] = @.transform(name, value) | |
@ | |
# Validations | |
# add a validation | |
add_validation: (name, error, fn)-> | |
@.validations.push | |
name: name | |
error: error | |
callback: fn | |
# Lets us know if the model is valid | |
valid: -> | |
@.validate().filter ({valid}) -> | |
not valid | |
.length is 0 | |
# Lets us know if the model is invalid | |
invalid: -> | |
not @.valid() | |
# Return an array of errors | |
errors: -> | |
@.validate().filter ({valid}) -> | |
not valid | |
.map ({name, message}) -> | |
message | |
# run the callbacks stored in the validations | |
# array. | |
validate: -> | |
self = @ | |
@.validations.map ({name, error, callback}) -> | |
name: name | |
message: error | |
valid: callback.call(self, self.attributes) | |
module.exports = Model |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment