Sha256: 3199c9d74d2bb521253a72263a25bb740f4865be7eeaff551f5f9ebd634d78db

Contents?: true

Size: 1.24 KB

Versions: 16

Compression:

Stored size: 1.24 KB

Contents

module CouchPotato
  module Persistence
    module Json
      def self.included(base) #:nodoc:
        base.extend ClassMethods
      end
      
      # returns a JSON representation of a model in order to store it in CouchDB
      def to_json(*args)
        to_hash.to_json(*args)
      end
      
      # returns all the attributes, the ruby class and the _id and _rev of a model as a Hash
      def to_hash
        (self.class.properties).inject({}) do |props, property|
          property.serialize(props, self)
          props
        end.merge(JSON.create_id => self.class.name).merge(id_and_rev_json)
      end
      
      private
      
      def id_and_rev_json
        ['_id', '_rev', '_deleted'].inject({}) do |hash, key|
          hash[key] = self.send(key) unless self.send(key).nil?
          hash
        end
      end
      
      module ClassMethods
        
        # creates a model instance from JSON
        def json_create(json)
          return if json.nil?
          instance = self.new
          instance._id = json[:_id] || json['_id']
          instance._rev = json[:_rev] || json['_rev']
          properties.each do |property|
            property.build(instance, json)
          end
          instance
        end
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 2 rubygems

Version Path
couch_potato-0.3.2 lib/couch_potato/persistence/json.rb
couch_potato-0.3.1 lib/couch_potato/persistence/json.rb
davber_couch_potato-0.3.0 lib/couch_potato/persistence/json.rb
couch_potato-0.3.0 lib/couch_potato/persistence/json.rb
couch_potato-0.2.32 lib/couch_potato/persistence/json.rb
couch_potato-0.2.31 lib/couch_potato/persistence/json.rb
couch_potato-0.2.30 lib/couch_potato/persistence/json.rb
couch_potato-0.2.29 lib/couch_potato/persistence/json.rb
couch_potato-0.2.28 lib/couch_potato/persistence/json.rb
couch_potato-0.2.27 lib/couch_potato/persistence/json.rb
couch_potato-0.2.26 lib/couch_potato/persistence/json.rb
couch_potato-0.2.25 lib/couch_potato/persistence/json.rb
couch_potato-0.2.24 lib/couch_potato/persistence/json.rb
couch_potato-0.2.23 lib/couch_potato/persistence/json.rb
couch_potato-0.2.22 lib/couch_potato/persistence/json.rb
couch_potato-0.2.21 lib/couch_potato/persistence/json.rb