Module: CouchCrumbs::Document

Defined in:
lib/couch_crumbs/document.rb

Overview

Document is an abstract base module that you mixin to your own classes to gain access to CouchDB document instances.

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Mixin our document methods



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/couch_crumbs/document.rb', line 415

def self.included(base)
  base.send(:include, InstanceMethods)
  base.extend(ClassMethods)
  # Override #initialize
  base.class_eval do
    
    # Set class variables
    class_variable_set(:@@crumb_type, base.name.split('::').last.downcase)
    class_variable_set(:@@database, CouchCrumbs::default_database)
    class_variable_set(:@@properties, [])
    
    # Accessors
    attr_accessor :uri, :raw
    
    # Override document #initialize
    def initialize(opts = {})
      raise ArgumentError.new("opts must be hash-like: #{ opts }") unless opts.respond_to?(:[])

      # If :json is present, we just parse it as an existing document
      if opts[:json]
        self.raw = JSON.parse(opts[:json])
      elsif opts[:hash]
        self.raw = opts[:hash]
      else
        self.raw = {}
        
        # Init special values
        raw["_id"] = opts[:id] || database.server.uuids
        raw["_rev"] = opts[:rev] unless opts[:rev].eql?(nil)
        raw["crumb_type"] = self.class.crumb_type
        raw["created_at"] = Time.now if self.class.properties.include?(:created_at)
        
        # Init named properties
        opts.each_pair do |name, value|
          send("#{ name }=", value)
        end
      end
      
      # This specific CouchDB document URI
      self.uri = File.join(database.uri, id)
      
      # Callback
      after_initialize
    end
    
  end
  
  # Create an advanced "all" view
  View.create!(base.design_doc, "all", View.advanced_json(File.join(File.dirname(__FILE__), "json", "all.json"), :crumb_type => base.crumb_type))
end