Class: Redis::Objects::Model
- Inherits:
-
Object
- Object
- Redis::Objects::Model
- Includes:
- Redis::Objects
- Defined in:
- lib/redis-objects-model.rb,
lib/redis-objects-model/version.rb
Overview
The simplest possible Model to use with redis-objects.
The minimum requirement for a class to be usable as a model with redis-objects is that it must provide an id attribute. So here is a base class that provides an id attribute - lazily yet atomically allocated using Redis, of course.
A few convenience methods are provided to allow you to check whether an id has been allocated, to do idiomatic ‘find’ type lookups, and to create with immediate id allocation.
Constant Summary collapse
- VERSION =
"1.0.1"
Class Method Summary collapse
-
.create ⇒ Object
Create a new object, persisting it immediately.
-
.find(id) ⇒ Object
Look up an object by id.
Instance Method Summary collapse
-
#id ⇒ Object
Retrieve the id of the object.
-
#initialize(id = nil) ⇒ Model
constructor
Create an instance of the model.
-
#new_record? ⇒ Boolean
Returns true if no id has been allocated for this object yet.
-
#persisted? ⇒ Boolean
Returns false if no id has been allocated for this object yet.
-
#redis_objects_model_next_id ⇒ Object
The name of the redis counter which will be used to allocate keys.
Constructor Details
#initialize(id = nil) ⇒ Model
Create an instance of the model.
If the id parameter is not nil, the model will be for the object with that id. Otherwise, you are creating a new object and a new id will be allocated atomically as needed.
34 35 36 |
# File 'lib/redis-objects-model.rb', line 34 def initialize(id = nil) @id = id end |
Class Method Details
.create ⇒ Object
Create a new object, persisting it immediately.
69 70 71 72 73 |
# File 'lib/redis-objects-model.rb', line 69 def self.create i = self.new i.id i end |
.find(id) ⇒ Object
Look up an object by id.
77 78 79 |
# File 'lib/redis-objects-model.rb', line 77 def self.find(id) self.new id end |
Instance Method Details
#id ⇒ Object
Retrieve the id of the object.
If the instance is referencing an existing object, the id of that object will be returned. Otherwise a new id will be allocated (and immediately saved).
In other words, accessing the id attribute is basically equivalent to persisting the object.
47 48 49 |
# File 'lib/redis-objects-model.rb', line 47 def id @id || @id = self.redis.incr(self.redis_objects_model_next_id) end |
#new_record? ⇒ Boolean
Returns true if no id has been allocated for this object yet.
57 58 59 |
# File 'lib/redis-objects-model.rb', line 57 def new_record? @id.nil? end |
#persisted? ⇒ Boolean
Returns false if no id has been allocated for this object yet.
63 64 65 |
# File 'lib/redis-objects-model.rb', line 63 def persisted? !new_record? end |
#redis_objects_model_next_id ⇒ Object
The name of the redis counter which will be used to allocate keys.
24 25 26 |
# File 'lib/redis-objects-model.rb', line 24 def redis_objects_model_next_id "#{self.class.redis_prefix}:next_id" end |