Class: Mouth::Record

Inherits:
Object
  • Object
show all
Defined in:
lib/mouth/record.rb

Overview

Simple base class to serve as an ORM for the mongo driver, without importing a large ORM like mongomapper.

Direct Known Subclasses

Dashboard, Graph

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Record

Returns a new instance of Record.



10
11
12
# File 'lib/mouth/record.rb', line 10

def initialize(attrs = {})
  self.attributes = normalize_attributes(attrs)
end

Instance Attribute Details

#attributesObject

Keys are symbols id is :id, not _id



8
9
10
# File 'lib/mouth/record.rb', line 8

def attributes
  @attributes
end

Class Method Details

.allObject



69
70
71
# File 'lib/mouth/record.rb', line 69

def self.all
  collection.find.to_a.collect {|d| new(d) }
end

.collectionObject



53
54
55
56
57
# File 'lib/mouth/record.rb', line 53

def self.collection
  demodularized = self.to_s.match(/(.+::)?(.+)$/)[2] || "record"
  tableized = demodularized.downcase + "s" # (: lol :)
  @collection ||= Mouth.mongo.collection(tableized)
end

.create(attributes) ⇒ Object



63
64
65
66
67
# File 'lib/mouth/record.rb', line 63

def self.create(attributes)
  r = new(attributes)
  r.save
  r
end

.find(id) ⇒ Object



59
60
61
# File 'lib/mouth/record.rb', line 59

def self.find(id)
  collection.find({"_id" => BSON::ObjectId(id)}).to_a.collect {|d| new(d) }.first
end

Instance Method Details

#all_attributesObject



14
15
16
# File 'lib/mouth/record.rb', line 14

def all_attributes
  self.attributes
end

#destroyObject



35
36
37
# File 'lib/mouth/record.rb', line 35

def destroy
  self.class.collection.remove({"_id" => BSON::ObjectId(self.attributes[:id])})
end

#normalize_attributes(attrs) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mouth/record.rb', line 39

def normalize_attributes(attrs)
  normalize = lambda do |h|
    hd = {}
    h.each_pair do |key, val|
      val = normalize.call(val) if val.is_a?(Hash)
      val = val.to_s if val.is_a?(BSON::ObjectId)
      # TODO: arrays :(
      hd[key.to_s == "_id" ? :id : key.to_sym] = val
    end
    hd
  end
  normalize.call attrs
end

#saveObject



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/mouth/record.rb', line 18

def save
  if self.attributes[:id]
    attrs = self.attributes.dup
    the_id = attrs.delete(:id).to_s
    doc = self.class.collection.update({"_id" => BSON::ObjectId(the_id)}, attrs)
  else
    self.class.collection.insert(self.attributes)
    self.attributes[:id] = self.attributes.delete(:_id).to_s
  end
  true
end

#update(new_attrs) ⇒ Object



30
31
32
33
# File 'lib/mouth/record.rb', line 30

def update(new_attrs)
  self.attributes = normalize_attributes(new_attrs)
  self.save
end