Class: Femto::Model::MongoAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/femto/model/mongo_adapter.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.clientObject

Returns the value of attribute client.



8
9
10
# File 'lib/femto/model/mongo_adapter.rb', line 8

def client
  @client
end

.dbObject

Returns the value of attribute db.



9
10
11
# File 'lib/femto/model/mongo_adapter.rb', line 9

def db
  @db
end

Class Method Details

.connect(options = nil) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/femto/model/mongo_adapter.rb', line 11

def connect(options=nil)
  if options
    @client = Mongo::Connection.new(options[:host], options[:port])
    @db = @client[options[:db]]
  else
    @client = Mongo::Connection.new
    @db = @client['test']
  end
end

.find(cls, query) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/femto/model/mongo_adapter.rb', line 30

def find(cls, query)
  results = []
  get_coll(cls).find(query).each do |res|
    model = cls.new(symbolize_keys(res))
    model.id = res['_id']
    results << model
  end
  results
end

.get_coll(cls) ⇒ Object



56
57
58
# File 'lib/femto/model/mongo_adapter.rb', line 56

def get_coll(cls)
  @db[cls.model_attrs[:storage_name]]
end

.remove(model) ⇒ Object



49
50
51
52
53
54
# File 'lib/femto/model/mongo_adapter.rb', line 49

def remove(model)
  coll = get_coll model.class
  if model.id
    coll.remove(:_id => model.id)
  end
end

.symbolize_keys(hash) ⇒ Object



60
61
62
# File 'lib/femto/model/mongo_adapter.rb', line 60

def symbolize_keys(hash)
  hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
end

.to_hash(model) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/femto/model/mongo_adapter.rb', line 21

def to_hash(model)
  result = {}
  model.class.model_attrs[:fields].each do |f|
    var = model.send f
    result[f] = var if var
  end
  result
end

.update(model) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/femto/model/mongo_adapter.rb', line 40

def update(model)
  coll = get_coll model.class
  if model.id
    coll.update({:_id => model.id}, model.to_hash)
  else
    model.id = coll.insert model.to_hash
  end
end