Sha256: ff0ef4b2f2c8b0acc30a3ccfeb7b59be78efcfa0e18eda69afe262ea3f8a30d2

Contents?: true

Size: 1.23 KB

Versions: 9

Compression:

Stored size: 1.23 KB

Contents

module CouchPotato
  module Persistence
    module Json
      def self.included(base)
        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('ruby_class' => 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

9 entries across 9 versions & 3 rubygems

Version Path
andrewtimberlake-couch_potato-0.2.8.1 lib/couch_potato/persistence/json.rb
andrewtimberlake-couch_potato-0.2.8.2 lib/couch_potato/persistence/json.rb
andrewtimberlake-couch_potato-0.2.8.3 lib/couch_potato/persistence/json.rb
andrewtimberlake-couch_potato-0.2.8.4 lib/couch_potato/persistence/json.rb
langalex-couch_potato-0.2.11 lib/couch_potato/persistence/json.rb
langalex-couch_potato-0.2.12 lib/couch_potato/persistence/json.rb
langalex-couch_potato-0.2.8 lib/couch_potato/persistence/json.rb
langalex-couch_potato-0.2.9 lib/couch_potato/persistence/json.rb
couch_potato-0.2.12 lib/couch_potato/persistence/json.rb