Sha256: 9180f00ace648f2b7055ebb1e6d977d058298a54cb11930e7f1b845b979a8cac

Contents?: true

Size: 1.33 KB

Versions: 29

Compression:

Stored size: 1.33 KB

Contents

require 'active_support/core_ext/hash'

module CouchPotato
  module Persistence
    module Json
      def self.included(base) #:nodoc:
        base.class_eval do
          extend ClassMethods
          attr_writer :_document

          def _document
            @_document ||= {}
          end
        end
      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 :_document => HashWithIndifferentAccess.new(json)
          instance._id = json[:_id] || json['_id']
          instance._rev = json[:_rev] || json['_rev']
          instance
        end
      end
    end
  end
end

Version data entries

29 entries across 29 versions & 1 rubygems

Version Path
couch_potato-1.18.0 lib/couch_potato/persistence/json.rb
couch_potato-1.17.0 lib/couch_potato/persistence/json.rb
couch_potato-1.16.0 lib/couch_potato/persistence/json.rb
couch_potato-1.15.0 lib/couch_potato/persistence/json.rb
couch_potato-1.14.0 lib/couch_potato/persistence/json.rb
couch_potato-1.13.0 lib/couch_potato/persistence/json.rb
couch_potato-1.12.1 lib/couch_potato/persistence/json.rb
couch_potato-1.12.0 lib/couch_potato/persistence/json.rb
couch_potato-1.11.0 lib/couch_potato/persistence/json.rb
couch_potato-1.10.1 lib/couch_potato/persistence/json.rb
couch_potato-1.10.0 lib/couch_potato/persistence/json.rb
couch_potato-1.9.0 lib/couch_potato/persistence/json.rb
couch_potato-1.7.1 lib/couch_potato/persistence/json.rb
couch_potato-1.7.0 lib/couch_potato/persistence/json.rb
couch_potato-1.6.5 lib/couch_potato/persistence/json.rb
couch_potato-1.6.4 lib/couch_potato/persistence/json.rb
couch_potato-1.6.3 lib/couch_potato/persistence/json.rb
couch_potato-1.4.0 lib/couch_potato/persistence/json.rb
couch_potato-1.3.0 lib/couch_potato/persistence/json.rb
couch_potato-1.2.0 lib/couch_potato/persistence/json.rb