Sha256: c0b634b40548d1f8a74e8cceba6d408914de1cc6fad4e1b6b520e72f5e927ec6

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

require 'active_support/json'

module MongoMapper
  module Plugins
    module Serialization
      extend ActiveSupport::Concern
      
      included do
        include ActiveModel::Serializers::JSON
        # Re-include this here otherwise we get run over by ActiveModel serialization
        include SerializableHash
        extend FromJson
      end

      module SerializableHash
        def serializable_hash options={}
          options ||= {}
          unless options[:only]
            methods = [options.delete(:methods)].flatten.compact
            methods << :id
            options[:methods] = methods.uniq
          end

          except = [options.delete(:except)].flatten.compact
          except << :_id
          options[:except] = except

          hash = super(options)
          hash.each do |key, value|
            if value.is_a?(Array)
              hash[key] = value.map do |item|
                item.respond_to?(:serializable_hash) ? item.serializable_hash(options) : item
              end
            elsif value.respond_to?(:serializable_hash)
              hash[key] = value.serializable_hash(options)
            end
          end
        end
      end

      module FromJson
        def from_json(json)
          self.attributes = ActiveSupport::JSON.decode(json)
          self
        end
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongo_mapper-rails3-0.7.0.1 lib/mongo_mapper/plugins/serialization.rb