Sha256: cff0c8664f0b17395713530597b3c894028298a5c40b08d2a7afc6efed01681a

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

module CouchPotato
  module Persistence
    module Json
      def self.included(base)
        base.extend ClassMethods
      end
      
      def to_json(*args)
        (self.class.properties).inject({}) do |props, property|
          property.serialize(props, self)
          props
        end.merge('ruby_class' => self.class.name).merge(id_and_rev_json).merge(timestamps_json).to_json(*args)
      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
      
      def timestamps_json
        [:created_at, :updated_at].inject({}) do |hash, key|
          hash[key] = self.send(key).to_s unless self.send(key).nil?
          hash
        end
      end
      
      module ClassMethods
        def json_create(json)
          instance = self.new
          instance.created_at = Time.parse(json['created_at']) 
          instance.updated_at = Time.parse(json['updated_at'])
          instance._id = json['_id']
          instance._rev = json['_rev']
          properties.each do |property|
            property.build(instance, json)
          end
          instance
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
langalex-couch_potato-0.1 lib/couch_potato/persistence/json.rb