Module: Candy::Piece::ClassMethods

Includes:
Crunch::ClassMethods
Defined in:
lib/candy/piece.rb

Instance Method Summary collapse

Methods included from Crunch::ClassMethods

#collection, #collection=, #connection, #connection=, #db, #db=, #index, #password, #password=, #username, #username=

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object

Deep magic! Finds and returns a single object by the named attribute.



38
39
40
41
42
43
44
45
46
# File 'lib/candy/piece.rb', line 38

def method_missing(name, *args, &block)
  if args.size == 1 or args.size == 2     # If we don't have a value, or have more than
    search = {name => args.shift}         # just a simple options hash, this must not be for us.
    search.merge!(args.shift) if args[0]  # We might have other conditions
    first(search)
  else
    super
  end
end

Instance Method Details

#embed(parent, attribute, *args) ⇒ Object

Creates the object with parent and attribute values set properly on the object and any children.



49
50
51
52
# File 'lib/candy/piece.rb', line 49

def embed(parent, attribute, *args)
  this = self.piece(*args)
  this.candy_adopt(parent, attribute)
end

#first(conditions = {}) ⇒ Object

Retrieves a single object from Mongo by its search attributes, or nil if it can’t be found.



17
18
19
20
21
22
# File 'lib/candy/piece.rb', line 17

def first(conditions={})
  conditions = {'_id' => conditions} unless conditions.is_a?(Hash)
  if record = collection.find_one(conditions)
    self.new(record)
  end
end

#piece(*args) ⇒ Object

Makes a new object with a given state that is not immediately saved, but is held in memory instead. The principal use for this is to embed it in other documents. Except for the unsaved state, this functions identically to ‘new’ and will pass all its arguments to the initializer. (Note that you can still embed documents that have been saved–but then you’ll have the data in two places.)



61
62
63
64
65
66
67
68
# File 'lib/candy/piece.rb', line 61

def piece(*args)
  if args[-1].is_a?(Hash)
    args[-1].merge!(EMBED_KEY => true)
  else
    args.push({EMBED_KEY => true})
  end
  self.new(*args)
end

#update(key_or_keys, fields) ⇒ Object

Performs an ‘upsert’ into the collection. The first parameter is a field name or array of fields which act as our “key” fields – if a document in the system matches the values from the hash, it’ll be updated. Otherwise, an insert will occur. The second parameter tells us what to set or insert.



28
29
30
31
32
33
34
# File 'lib/candy/piece.rb', line 28

def update(key_or_keys, fields)
  search_keys = {}
  Array(key_or_keys).each do |key|
    search_keys[key] = Wrapper.wrap(fields[key])
  end
  collection.update search_keys, fields, :upsert => true
end