Skip to content

Instantly share code, notes, and snippets.

@jondeandres
Created May 5, 2013 17:41
Show Gist options
  • Save jondeandres/5521527 to your computer and use it in GitHub Desktop.
Save jondeandres/5521527 to your computer and use it in GitHub Desktop.
redis = require('redis')
client = redis.connect('127.0.0.1', 6379)
class RedisModel
@primary_key: "id"
@model: nil
@counters: {}
-- class methods
@counter: =>
client\get(@counter_key!)
@increment_counter: =>
client\incrby(@counter_key!, 1)
@counter_key: =>
@_counter_key = @_counter_key or @model .. ":count"
@_counter_key
@get: (id) =>
client\get(id)
-- instance methods
new: (id) =>
@spawn_methods!
counter_key_for: (counter) =>
@\key! .. ':' .. counter
get_counter: (counter) =>
value = client\get(@\counter_key_for(counter))
value or 0
inc_counter: (counter) =>
client\incrby(@\counter_key_for(counter), 1)
decr_counter: (counter) =>
client\decrby(@\counter_key_for(counter), 1)
spawn_methods: =>
__index = getmetatable(@).__index
-- spawn counter methods
for counter in *@@counters
-- count
name = counter .. '_count'
__index[name] = ->
@\get_counter counter
-- inc
name = 'incr_' .. counter
__index[name] = ->
@\inc_counter(counter)
-- decr
name = 'decr_' .. counter
__index[name] = ->
@\decr_counter counter
key: =>
@_key = @_key or @@model .. ":" .. @@primary_key .. ":" .. @id
@_key
save: =>
if not @id
@@increment_counter!
@id = @@counter!
@_save!
attributes: =>
tbl = {}
for attr in *@@attrs
tbl[attr] = @[attr]
tbl
_save: =>
client\hmset(@key!, @\attributes!)
class User extends RedisModel
@model: "users"
@attrs: { 'name' }
@counters: {'foo', 'faa'}
user1 = User!
user1.name = 'Jon'
user1\save!
user1\incr_foo!
user1\decr_foo!
print user1\foo_count!
print user1\faa_count!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment