Class: Bookit::PersistableObject

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Serialization
Defined in:
lib/bookit/persistable_object.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ PersistableObject

Returns a new instance of PersistableObject.



41
42
43
44
# File 'lib/bookit/persistable_object.rb', line 41

def initialize(params = {})
  @attributes = params
  @id = params[:id] || nil
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



9
10
11
# File 'lib/bookit/persistable_object.rb', line 9

def attributes
  @attributes
end

#idObject

Returns the value of attribute id.



9
10
11
# File 'lib/bookit/persistable_object.rb', line 9

def id
  @id
end

Class Method Details

.find(id) ⇒ Object

specifically use the generic initializer to rebuild object



22
23
24
25
26
# File 'lib/bookit/persistable_object.rb', line 22

def find(id)
  return nil unless redis.exists key(id)

  new redis.hgetall(key(id)).to_options
end

.key(id) ⇒ Object



17
18
19
# File 'lib/bookit/persistable_object.rb', line 17

def key(id)
  "#{namespace}:%s" % id
end

.lastObject



32
33
34
# File 'lib/bookit/persistable_object.rb', line 32

def last
  find last_id
end

.last_idObject



28
29
30
# File 'lib/bookit/persistable_object.rb', line 28

def last_id
  redis.get key("LAST_ID")
end

.namespaceObject



13
14
15
# File 'lib/bookit/persistable_object.rb', line 13

def namespace
  @namespace || self
end

.redis(host = "localhost", port = 6379) ⇒ Object



36
37
38
# File 'lib/bookit/persistable_object.rb', line 36

def redis(host="localhost", port=6379)
  @redis ||= Redis.new(host: host, port: port)
end

Instance Method Details

#clearObject



67
68
69
# File 'lib/bookit/persistable_object.rb', line 67

def clear
  redis.del key
end

#key(id = @id) ⇒ Object



55
56
57
# File 'lib/bookit/persistable_object.rb', line 55

def key(id=@id)
  self.class.key(id)
end

#persistObject

store in redis



60
61
62
63
64
65
# File 'lib/bookit/persistable_object.rb', line 60

def persist
  @attributes[:id] = @id = incr_key

  redis.hmset key, *serializable_hash.flatten
  self
end

#read_attribute_for_validation(key) ⇒ Object Also known as: []



50
51
52
# File 'lib/bookit/persistable_object.rb', line 50

def read_attribute_for_validation(key)
  @attributes[key]
end

#redisObject



46
47
48
# File 'lib/bookit/persistable_object.rb', line 46

def redis
  self.class.redis
end